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}}))
Ps:
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
有意义的希望
详细了解 filter
这篇关于JavaScript从对象数组获取不在另一个数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!