2010-08-20 4 views
1

Comment interroger un objet avec un tableau?Interrogation d'objets avec un tableau (sans script tiers)

var myArray = ['A','C'] 

En utilisant monTableau, comment puis-je obtenir un tableau retourné avec [ « 1 », « 3 »] sur les éléments suivants (anciennement objet JSON) (sans l'aide d'un script de requête tiers - à moins que c'est jQuery:)

[ { "property1": "1", 
    "property2": "A" 
    }, 
    { "property1": "2", 
    "property2": "B" 
    }, 
    { "property1": "3", 
    "property2": "C" 
    } ] 

Répondre

4

Vous pourriez une boucle imbriquée:

var myArray = ['A','C']; 
var json = [{ 
    'property1': '1', 
    'property2': 'A' 
}, { 
    'property1': '2', 
    'property2': 'B' 
}, { 
    'property1': '3', 
    'property2': 'C' 
}]; 

var result = new Array(); 
for (var i = 0; i < myArray.length; i++) { 
    for (var j = 0; j < json.length; j++) { 
     if (json[j].property2 === myArray[i]) { 
      result.push(json[j].property1); 
     } 
    } 
} 

// at this point result will contain ['1', '3'] 
+0

Darin !! Solution douce! Merci pour mon '1' et '3': D – Kyle

2

Vous pouvez marcher le tableau comme celui-ci:

var json = [ { "property1": "1", 
    "property2": "A" 
    }, 
    { "property1": "2", 
    "property2": "B" 
    }, 
    { "property1": "3", 
    "property2": "C" 
    } ]; 

var myArray = ['A', 'C']; // Here is your request 
var resultArray = []; // Here is the container for your result 

// Walking the data with an old-fashioned for loop 
// You can use some library forEach solution here. 
for (var i = 0, len = json.length; i < len; i++) { 
    var item = json[i]; // Caching the array element 

    // Warning! Not all browsers implement indexOf, you may need to use a library 
    // or find a way around 
    if (myArray.indexOf(item.property2) !== -1) { 
     resultArray.push(item.property1); 
    } 
} 

console.log(resultArray); 
+0

+1 merci Igor pour cette solution! semble être une bonne solution alternative. – Kyle

+0

Ce n'est vraiment pas une alternative :) C'est pareil sauf pour la partie 'indexOf'. Je suis vraiment surpris par la proximité de la réponse d'Emile, car je n'ai pas vu sa solution avant de répondre à cette question. –

Questions connexes