Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  112] [ 7]  / answers: 1 / hits: 13256  / 4 Years ago, wed, october 28, 2020, 12:00:00

I'm trying to concat two arrays of objects with lodash. I have these two array and I use concat operator in this way:


 var array1 = [{ id: 1, name: 'doc1' }, { id: 2, name: 'doc2' }];
var array2 = [{id:1, name:'doc1'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}];

var array3 = _.concat(array1, array2);

I would like an array like this


 [{id:1, name:'doc1'}, {id:2, name:'doc2'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}]]

But with concat function I obtain an array like this:


  [{ id: 1, name: 'doc1' }, { id: 1, name: 'doc1' }, { id: 2, name: 'doc2' }, { id: 3, name: 'doc3' }, { id: 4, name: 'doc4' }]]

I want to avoid the repetition of an object with the same id...Which kind of operator can I use?


More From » typescript

 Answers
4

You can get the result using merge and keyBy lodash functions.




var array1 = [{id:1, name:'doc1'}, {id:2, name:'doc2'}];
var array2 = [{id:1, name:'doc1'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}];

var merged = _.merge(_.keyBy(array1, 'id'), _.keyBy(array2, 'id'));
var values = _.values(merged);
console.log(values);

<script src=https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js></script>




[#2406] Friday, October 23, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayla

Total Points: 681
Total Questions: 102
Total Answers: 108

Location: Marshall Islands
Member since Tue, Sep 21, 2021
3 Years ago
tayla questions
Fri, Mar 5, 21, 00:00, 3 Years ago
Thu, Apr 9, 20, 00:00, 4 Years ago
Mon, Dec 9, 19, 00:00, 5 Years ago
;