I have 2 array of objects:
const arr1 = [{'id':'1' 'value':'yes'}, {'id':'2', 'value':'no'}];
const arr2 = [{'id':'2', 'value':'yes'}];
So, if I try and merge these 2 arrays the result should be:
arrTemp = [{'id':'1', 'value':'yes'}, {'id':'2', 'value':'yes'}];
Basically, it should work similar to Object.assign(), but no matter what I try it does not work. Could anyone please help me in this ?
I modified the data structure. Is it possible to merge them now and get the output.
Thanks
You could take a
Map
as reference to the new assigned object in the result array and build first a new array with a copy of the objects and then iterate the second array and update the objects with the same key.You could work with a valid ES6 data structure like a map for example:
const 1 = { 1: { string: 'yes' }, 2: { string: 'no' } } const 2 = { 2: { string: 'yes' }, 3: { string: 'no' } } const 3 = { ...1, ...2}
This will override your first argument with the second one or just combine them where possible. Just try it out in your browser it's a lot easier and enhances performance since you will never have to use
findById()
which is an expensive operation.In javascript, arrays are simply objects indexed by numbers starting from 0.
So when you use
Object.assign
onarr1
andarr2
you will override the first item in thearr1
with the first item inarr2
because they are both indexed under the key0
.your result will be:
(or in object syntax:)
Instead of using arrays, you could create an object indexed by the number string (which is how you seem to be thinking of the array in any case).
So you could change your original data structure to make the job easier:
For anyone finding this answer at a later point in time. There are a couple of ways that you could want this to work exactly, but you could filter all adjusted elements in the first array, and then combine it with the second array.
Alternatively, you could update the elements in the first array, and then filter them from the second array instead.
This is how you can get the job done with ES6 spread, reduce and Object.values.
simple way to add with exist array of object: