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

前端 未结 6 1671
孤独总比滥情好
孤独总比滥情好 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:08

    The same result can be achieved using Lodash.

    var result1 = [
        {id:1, name:'Sandra', type:'user', username:'sandra'},
        {id:2, name:'John', type:'admin', username:'johnny2'},
        {id:3, name:'Peter', type:'user', username:'pete'},
        {id:4, name:'Bobby', type:'user', username:'be_bob'}
    ];
    
    var result2 = [
        {id:2, name:'John', email:'johnny@example.com'},
        {id:4, name:'Bobby', email:'bobby@example.com'}
    ];
    
    var result3 = _(result1) 
            .differenceBy(result2, 'id', 'name')
            .map(_.partial(_.pick, _, 'id', 'name'))
            .value();
    
    console.log(result3);

    You can get the desired result applying a difference between both arrays using the properties "id" and "name" as a way to "link" elements between them. If any of those properties are different, the elements are considered different (improbably in your case because id seems to be unique).

    Lastly, you have to map the result in order to "omit" the undesired properties of the object.

    Hope it helps.

提交回复
热议问题