如何在对象数组中查找一个对象的所有匹配键和值?

时间:2017-07-20 02:10:11

标签: javascript arrays object

我需要一个循环遍历对象数组的代码,检查键和值是否与单独对象中的键匹配,然后在新数组中推送包含所有键和值的对象,因此对于特定情况:

var arr = [{name: 'john', lastname: 'roberts', children: 3},
           {name: 'john', lastname: 'green', children: null}, 
           {name: 'steve', lastname: 'baker', children: 3}];

var obj = {name: 'john', children: 3};

结果将是:

arr2 = [{name: 'john', lastname: 'roberts', children: 3}];

2 个答案:

答案 0 :(得分:2)

扩展@Psidom版本



var arr = [{name: 'john', lastname: 'roberts', children: 3},
           {name: 'john', lastname: 'green', children: null}, 
           {name: 'steve', lastname: 'baker', children: 3}];

var obj = {name: 'john', children: 3};

console.log(
  arr.filter(x => Object.keys(obj).every( k => x[k] == obj[k]))
);




答案 1 :(得分:1)

在数组上使用filter

var arr = [{name: 'john', lastname: 'roberts', children: 3},
           {name: 'john', lastname: 'green', children: null}, 
           {name: 'steve', lastname: 'baker', children: 3}];

var obj = {name: 'john', children: 3};

console.log(
  arr.filter(x => x.name === obj.name && x.children === obj.children)
);