如何使用数组查询对象?
var myArray = ['A','C']
使用myArray,如何从以下(先前为JSON对象)中返回['1','3']的返回数组(不使用第三方查询脚本-除非是jQuery :)
[ { "property1": "1",
"property2": "A"
},
{ "property1": "2",
"property2": "B"
},
{ "property1": "3",
"property2": "C"
} ]
最佳答案
您可以嵌套循环:
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']