This question already has answers here:
Compare the elements of two arrays by Id and remove the elements from the one array that are not presented in the other
                                
                                    (3个答案)
                                
                        
                                3年前关闭。
            
                    
我有这个javascript对象:

var arr1 = [{id:'124',name:'qqq'},
           {id:'589',name:'www'},
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}]

var arr2 = [{id:'124',name:'ttt'},
           {id:'45',name:'yyy'}


从arr1中,我需要删除arr2中具有相同ID的所有对象。

这是arr1的预期结果:

var arr1 = [{id:'589',name:'www'},
           {id:'567',name:'rrr'}]


用JavaScript实现它的优雅方法是什么?

最佳答案

这是一种动态获取ID值的方法。它通过thisthe optional thisArg argument将中间对象绑定到filter



var arr1 = [{id:'124',name:'qqq'},
           {id:'589',name:'www'},
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}];

var arr2 = [{id:'124',name:'ttt'},
           {id:'45',name:'yyy'}];

arr1 = arr1.filter(function (el) {
    return !this[el.id];
}, arr2.reduce(function (obj, el) {
    return obj[el.id] = 1, obj;
}, {}));

console.log(arr1);





作为filter的最后一个参数传递的中间对象如下所示:

{ 45: 1, 124: 1 }


这使得检查arr1的元素是否需要被拒绝变得很简单。

关于javascript - 如何通过属性值从数组中删除对象? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37908505/

10-12 00:31
查看更多