JavaScript 从一个对象数组中获取不在另一个数组中的元素 [英] JavaScript get elements from an object array that are not in another
问题描述
我是 JavaScript 编程新手,我有两个具有以下结构的对象数组:
I'm new in JavaScript programming and I have two object arrays that have the following structure:
myFirstObjArray = [{foo: 1, bar: 1}, {foo: 3, bar: 3}, {foo: 4, bar: 5}];
mySecondObjArray = [{foo: 2}, {foo: 4}, {foo: 5}];
我需要获取两个单独的数组,其中包含键 foo
的值,第一个包含第一个数组中但不在第二个数组中的数组,基于键 的值foo
,第二个在 mySecondObjArray
但不在 myFirstObjArray
中.
I need to get two separate arrays containing the values of key foo
, the first containing the ones that are in the first array but not in the second, based on the value of key foo
, and the second that are in mySecondObjArray
but not in myFirstObjArray
.
有没有办法做到这一点
for(i=0;i<myFirstObjArray.length;i++)
for(j=0;j<mySecondObjArray .length;j++)
{...build first array here}
for(i=0;i<mySecondObjArray .length;i++)
for(j=0;j<myFirstObjArray.length;j++)
{...build second array here}
?也许我的问题是我没有找到的重复问题,所以请温柔.
? Perhaps my question is a duplicate one that I didn't find, so please be gentle.
预期输出:
firstArray = [{foo: 1}, {foo: 3}];
secondArray = [{foo: 2}, {foo: 5}];
推荐答案
您可以通过设置基于其他数组元素的条件来简单地过滤一个数组的元素.
You can simply filter one array's elements by setting the condition based on other array's elements like.
var myFirstObjArray = [{foo: 1, bar: 1}, {foo: 3, bar: 3}, {foo: 4, bar: 5}],
mySecondObjArray = [{foo: 2}, {foo: 4}, {foo: 5}],
firstArray = myFirstObjArray.filter(o=> !mySecondObjArray.some(i=> i.foo === o.foo));
secondArray = mySecondObjArray.filter(o=> !myFirstObjArray.some(i=> i.foo === o.foo));
console.log(firstArray.map(o=> {return {'foo' : o.foo}}))
console.log(secondArray.map(o=> {return {'foo' : o.foo}}))
附:
some()
方法测试数组中是否至少有一个元素通过了提供的函数实现的测试.我添加了一个函数,它只检查 foo
属性是否存在于另一个具有相同值的数组中,以便能够从第一个数组中进行过滤.
The some()
method tests whether at least one element in the array passes the test implemented by the provided function. And I've added a function which just checks if foo
property exists in the other array with the same value to be able to filter from the first array.
最后可以使用.map
来过滤掉想要的键值对
At the end you can use .map
to filter out the desired key value pairs
希望有意义
这篇关于JavaScript 从一个对象数组中获取不在另一个数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!