How to combine an array of objects with js underscore

I have an array of such objects:

array1 = [ {field: 'username', display: 'username', hide: true}, {field: 'age', display: 'Age', hide: true}, {field: 'height', display: 'Height', hide: true} ] 

Then I have array2:

 array2 = [ {field: 'username', display: 'username 123', hide: false}, {field: 'age', hide: false} ] 

I want to combine these two arrays by their field, i.e. The final result should be:

 array3 = [ {field: 'username', display: 'username 123', hide: false}, {field: 'age', display: 'Age', hide: false}, {field: 'height', display: 'Height', hide: true} ] 

I tried var newObj = _.extend(array1, array2); but he did not give me what I want.

+6
source share
1 answer

There is no function that will do this, as it is a fairly specialized operation. However, its rather simple composition of underlining functions:

 _.values(_.extend(_.indexBy(array1, 'field'), _.indexBy(array2, 'field'))) 

We use indexBy to turn arrays into objects bound to the field value, and then extend does what we want. Finally, values returns it back to the array.

Note that while this does not guarantee any guarantees regarding order, in the current _ and v8 implementations, the final array will be things from array1 , followed by things from array2 that are not in array1 , sorted in the original order of each array.

Also note that the _.extend function is destructive in the first argument, while this does not change any array.

If you want to be sure that the order matches the original array1 :

 order = _.object(_.map(array1, function(obj, i) { return [obj.field, i]; })) _.sortBy(_.values(_.extend(_.indexBy(array1, 'field'), _.indexBy(array2, 'field'))), function(obj) { order[obj.field]; }) 

Here we create a position search table, and then sort the original solution based on the search table.

+10
source

Source: https://habr.com/ru/post/979888/


All Articles