我需要一个循环遍历对象数组的代码,检查键和值是否与单独对象中的键匹配,然后在新数组中推送包含所有键和值的对象,因此对于特定情况:
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}];
答案 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)
);