Comparing two arrays of objects, and exclude the elements who match values into new array in JS

前端 未结 6 1670
孤独总比滥情好
孤独总比滥情好 2020-11-28 03:57

here is my use case in JavaScript:

I have two arrays of objects which have properties that match (id & name).

var result1 = [
    {id:1, name:\'S         


        
6条回答
  •  失恋的感觉
    2020-11-28 04:25

    I have searched a lot for a solution in which I can compare two array of objects with different attribute names (something like a left outer join). I came up with this solution. Here I used Lodash. I hope this will help you.

    var Obj1 = [
        {id:1, name:'Sandra'},
        {id:2, name:'John'},   
    ];
    
    var Obj2 = [
        {_id:2, name:'John'},
        {_id:4, name:'Bobby'}
    ];
    
    var Obj3 = lodash.differenceWith(Obj1, Obj2, function (o1, o2) {
        return o1['id'] === o2['_id']
    });
    
    console.log(Obj3);
    //  {id:1, name:'Sandra'}
    

提交回复
热议问题