使用数组查询对象(不包含第三方脚本)
问题描述:
如何使用数组查询对象?使用数组查询对象(不包含第三方脚本)
var myArray = ['A','C']
使用myArray的,我怎么能得到与[“1”,“3”]返回的数组了以下(以前JSON对象)的(不使用第三方查询脚本 - 除非它是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']
答
您可以步行数组是这样的:
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感谢伊戈尔为此解决方案!似乎是一个很好的替代解决方案。 – Kyle 2010-08-20 11:41:49
+0
这真的不是替代方法:)除了'indexOf'部分外,它是一样的。我真的很惊讶与Emile的回答有多接近,因为在回答这个问题之前我没有看到他的解决方案。 – 2010-08-20 11:47:40
Darin !!甜蜜的解答!谢谢我的'1'和'3':D – Kyle 2010-08-20 11:40:42