简体   繁体   English

从另一个对象数组中删除对象数组

[英]Remove array of objects from another array of objects

Assume we have the following arrays of objects to be compared based on property id :假设我们有以下对象数组要根据属性id进行比较:

a = [{'id':'1', 'name':'a1'}, {'id':'2', 'name':'a2'}, {'id':'3', 'name':'a3'}]

and

b = [[{'id':'2', 'name':'a2'}, ]

How can I subtract b from a?如何从 a 中减去 b? So that we have c = a - b which should be equal to [ {'id':'1', 'name':'a1'}, {'id':'3', 'name':'a3'}] .所以我们有c = a - b应该等于[ {'id':'1', 'name':'a1'}, {'id':'3', 'name':'a3'}]

I have tried using this:我试过用这个:

var c= a.filter(function(item) {
                    return !b.includes(item.id);
                });

but still not working.但仍然无法正常工作。

How about this solution?这个解决方案怎么样? It assumes that 'b' is also an array so for each element of 'a' you check if there is a matching object in 'b'.它假定“b”也是一个数组,因此对于“a”的每个元素,您检查“b”中是否有匹配的对象。 If there is a matching object then return a false in the filter function so that that element is discarded.如果存在匹配的对象,则在过滤器函数中返回 false 以便丢弃该元素。

 var a = [{ 'id': '1', 'name': 'a1' }, { 'id': '2', 'name': 'a2' }, { 'id': '3', 'name': 'a3' }] var b = [{ 'id': '2', 'name': 'a2' }] var c = a.filter(function(objFromA) { return !b.find(function(objFromB) { return objFromA.id === objFromB.id }) }) console.log(c)

Here is a nice one line answer :)这是一个很好的单行答案:)

Basically, you can filter, as you were trying to do already.基本上,您可以过滤,就像您已经尝试做的那样。 Then you can also filter b for each a element and if the length of the filtered b is zero, then you return true because that means the a element is unique to a.然后,您还可以为每个 a 元素过滤 b,如果过滤后的 b 的长度为零,则返回 true,因为这意味着 a 元素对于 a 是唯一的。

 var a = [{ 'id': '1', 'name': 'a1' }, { 'id': '2', 'name': 'a2' }, { 'id': '3', 'name': 'a3' }]; var b = [{ 'id': '2', 'name': 'a2' }]; c = a.filter( x => !b.filter( y => y.id === x.id).length); console.log(c);

First, you build just a map of the ids you want to delete.首先,您只构建要删除的 id 的映射。 Then, you filter your first array with it, like that:然后,你用它过滤你的第一个数组,就像这样:

 var a = [{ 'id': '1', 'name': 'a1' }, { 'id': '2', 'name': 'a2' }, { 'id': '3', 'name': 'a3' }]; var b = [{ 'id': '2', 'name': 'a2' }]; var idsToDelete = b.map(function(elt) {return elt.id;}); var result = a.filter(function(elt) {return idsToDelete.indexOf(elt.id) === -1;}); console.log(result)

Easy with new ES6 Syntax轻松使用新的 ES6 语法

Second and Third way are more performant i guess....我猜第二种和第三种方式的性能更高......

a.filter(i => !b.filter(y => y.id === i.id).length); // One Way
a.filter(i => !b.find(f => f.id === i.id)); // Second Way
a.filter(i => b.findIndex(f => f.id === i.id)) // Third Way

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM