根据javascript中的另一个对象数组过滤对象数组 [英] Filter array of objects based on another array of objects in javascript
本文介绍了根据javascript中的另一个对象数组过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的数组
arr1 =
[
{A: 'red', B: 'blue'},
{Q: 'green', R: 'blue'},
{B: 'green', M: 'red'},
{Q: 'white', R: 'blue'},
...
]
每个对象都有两个键/值对,一个字母和一个颜色。我有另一个这样的数组
Each object has two key/value pairs, a letter and color. I have another array like this
filter=
[
{A: 'val', B: 'someval'},
{B: 'anothervalue', M: 'value'}
]
是否可以过滤第一个数组,使得最终结果是一个只有与第二个数组具有相同键的对象的数组。 (没有for或while循环)
Is it possible to filter the first array such that the final result is an array that only has the objects that have the same keys as the second array. (without a for or while loop)
在这种情况下,它将是:
In this scenario it would be:
[
{A: 'red', B: 'blue'},
{B: 'green', M: 'red'}
]
所以我想要这样的东西:
So I want something like:
let filteredArr = arr1.filter(obj =>
Object.keys(obj) == Object.keys(filter[someKey]));
但我不知道如何在不循环<$ c $的所有键的情况下执行此操作c>过滤器。
But I'm not sure how to do this without looping over all the keys of filter
.
推荐答案
您可以使用 设置
的属性名称并过滤数组。
You could use a Set
for the property names and filter the array.
var array = [{ A: 'red', B: 'blue' }, { Q: 'green', R: 'blue' }, { B: 'green', M: 'red' }, { Q: 'white', R: 'blue' }],
filter = [{ A: 'val', B: 'someval' }, { B: 'anothervalue', M: 'value' }],
getKey = o => Object.keys(o).sort().join('|'),
result = array.filter((s => o => s.has(getKey(o)))(new Set(filter.map(getKey))));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于根据javascript中的另一个对象数组过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文