views:

76

answers:

2

I'm 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

A: 

Ah man, jQuery would make it easy if you could be sure they'd never collide:

var annotations = $.extend.apply($, status['annotations'] || []);
var annotation = annotations['myAnnotationType'];

I guess you could write your own budget extend:

function collapse(annotations) {
  var result = {};
  for (var i = 0; i < annotations.length; i++) {
    var annotation = annotations[i];
    for (var key in annotation) {
      if (annotation.hasOwnProperty(key)) {
        result[key] = annotation[key]; // Using a deep cloning function possible here
      }
    }
  }
  return result;
}

Or you could have a hack at adapting jQuery's extend.

wombleton
A: 

If I understand the purpose of this function correctly, you are trying to return the first object in an array (status.annotations) that contains a key (type)

function getAnnotation(status, type){
  for (var i=0; i<status.annotations.length ; i++) {
    var obj = status.annotations[i];
    if (obj.hasOwnProperty(type)) return obj;
  }
}
gnarf