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

标签 javascript jquery arrays json

如何使用数组查询对象?

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/

相关文章:

javascript - 二项式子数组

javascript - 如何使用 React JS 导出多个类组件?

javascript - 隐藏/显示所有图像切换按钮

javascript - 如何找到最接近目标数组的数字数组?

javascript - 映射数据给出了正确的结果,但最终在 final方法中结果为未定义

C++ - 如何将 char 附加到 char[]?

javascript - React - 传递 Prop ,导航器中的设置错误?

javascript - Ext JS 6.5 菜单自动隐藏

javascript - 将表单输入传递给 highcharts 然后重建图表

javascript - 禁用 jquery 中的事件链接