gpt4 book ai didi

javascript - 使用数组查询对象(没有第 3 方脚本)

转载 作者:行者123 更新时间:2023-11-30 08:16:14 26 4
gpt4 key购买 nike

如何使用数组查询对象?

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']

关于javascript - 使用数组查询对象(没有第 3 方脚本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3530351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com