简体   繁体   English

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

[英]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.

相关问题 从对象数组中查找匹配的对象键 - Find matching object keys from an array of objects 如何通过匹配所有值而不是一个来过滤对象数组 - How to filter the array of object by matching all values instead of one 如何获取具有多个键的对象数组中所有键的值,然后将它们全部相加[暂停] - How to get values of all keys in array of objects with more than one keys and then sum of them all [on hold] 如何使用这些键及其值将具有一个 object 和多个键的数组转换为多个对象的数组? - How to convert an array with one object and multiple keys into an array of multiple objects using those keys and their values? 如何使用键数组在对象的对象中查找值 - How to find a value in object of objects with an array of keys 如何在具有匹配值的对象数组中删除 object - How to remove object in array of objects with matching values 如何找到对象中所有值的总和以及数组中包含的对象的总和? - How find sum of all values in object and included objects in array? 如何根据嵌套对象数组的对象搜索输入查找所有匹配值 - how to find all matching values based on search input of objects for the nested array of objects 如何减少包含匹配键/值+变体的对象数组? - How to Reduce An Array of Objects That Contain Matching Keys/Values + Variations? 在对象数组中添加匹配键的值 - Add values of matching keys in array of objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM