2010-05-30 4 views
0

Je travaille avec le dernier brouillon de l'api de twitter annotations. Un bit exemple de données ressembleobtenir une clé sur un hachage javascript

status { 
    annotations : [ 
     {myAnnotationType:{myKey:myValue}}, 
     {someoneElsesAnnotationType:{theirKey:theirValue}}, 
    ] 
} 

maintenant je veux vérifier un statut pour voir si elle a une annotation avec myAnnotationType en elle. Si les annotations étaient un hachage au lieu d'un tableau, je pourrais simplement écrire var ann = status.annotations.myAnnotationType. Mais ce ne est pas si je l'ai écrit ceci:

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"); 

Il doit y avoir une meilleure façon! Y a-t-il?

PS Je ne peux pas utiliser jquery ou quoi que ce soit comme cela est js à utiliser dans un widget caja et le conteneur ne si vous pouviez supporte pas libs externes

Répondre

0

Si je comprends le but de cette fonction correctement, vous essayez de renvoyer le premier objet dans un tableau (status.annotations) qui contient une clé (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; 
    } 
} 
0

homme Ah, jQuery serait le rendre facile être sûr ils avaient jamais entrer en collision:

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

Je suppose que vous pouvez écrire votre propre 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; 
} 

Ou vous pourriez avoir un hack à adapter jQuery de extend.

Questions connexes