What's the correct way to merge two arrays in Javascript?
I've got two arrays (for example):
var a1 = [{ id : 1, name : "test"}, { id : 2, name : "test2"}]
var a2 = [{ id : 1, count : "1"}, {id : 2, count : "2"}]
I want to be able to end up with something like:
var a3 = [{ id : 1, name : "test", count : "1"},
{ id : 2, name : "test2", count : "2"}]
Where the two arrays are being joined based on the 'id' field and extra data is simply being added.
I tried to use _.union
to do this, but it simply overwrites the values from the second array into the first one
reduce version.
I think it's common practice in functional language.
The lodash implementaiton:
The result:
This should do the trick:
This assumes that the id of the second object in a1 should be 2 rather than "2"
You can write a simple object merging function like this
Next, you need to do use a double-loop to apply it to your data structre
You can also use
mergeObject
as a simple clone, too, by passing one parameter as an empty object.ES6 simplifies this:
Note that repeated keys will be merged, and the value of the second object will prevail and the repeated value of the first object will be ignored.
Example:
Assuming IDs are strings and the order does not matter, you can
Object.assign
(ES6, can be polyfilled).In ECMAScript6, if the IDs are not necessarily strings, you can use
Map
: