getting a key out of a javascript hash
        Posted  
        
            by mcintyre321
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by mcintyre321
        
        
        
        Published on 2010-05-30T01:42:51Z
        Indexed on 
            2010/05/30
            1:52 UTC
        
        
        Read the original article
        Hit count: 347
        
I working with the latest draft of the twitter annotations api. An example bit of data looks like
status {
     annotations : [
         {myAnnotationType:{myKey:myValue}},
         {someoneElsesAnnotationType:{theirKey:theirValue}},
     ]
}
now i want to check a status to see if it has an annotation with myAnnotationType in it. If annotations was a hash instead of an array I could just write var ann = status.annotations.myAnnotationType. But its not so I wrote this instead:
function getKeys(obj){
    var keys = [];
    for (key in obj) {
        if (obj.hasOwnProperty(key)) { keys[keys.length] = key; }
    } 
    return keys;
}
function getAnnotation(status, type){
     for(var i=0;i<status.annotations.length;i++){
         var keys = getKeys(status.annotations[i]);
         for(var j=0;j<keys.length;j++){
             if(keys[j] == type){
                 return status.annotations[i];
             }
         }
     }
}
var ann = getAnnotation(status, "myAnnotationType");
There must be a better way! Is there?
PS I can't use jquery or anything as this is js to be used in a caja widget and the container doesn't support external libs
© Stack Overflow or respective owner