[英]How to find all matching keys and values of one object in array of objects?
I need a code which would loop through an array of objects and check if keys and values match with ones in a separate object, and then push object that contains all keys and values in a new array, so for a specific case: 我需要一个代码,该代码将遍历对象数组,并检查键和值是否与单独对象中的键和值匹配,然后将包含所有键和值的对象推入新数组中,因此对于特定情况:
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};
result would be: 结果将是:
arr2 = [{name: 'john', lastname: 'roberts', children: 3}];
expanding @Psidom version 扩展@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])) );
Use filter
on the Array: 在数组上使用
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) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.