Skip to content
Advertisement

Compare and update two arrays without losing mutated data

I have an array of objects contains data of persons

JavaScript

then I add data to this array to each element where I end up with new key called money with value of 20 as the following

JavaScript

and the array becomes like this

JavaScript

Now, I have a new array with new data (new person) but missing the money I have added before. (careful person with id 2 is not there)

JavaScript

I want to update the old array with new data but also keep the mutated data, and I want the result to end up like this:

JavaScript

Thanks for the help.

Advertisement

Answer

Just a note: map creates a whole new array, it doesn’t make sense to use it for just mutating the contents. Use forEach or just a regular for loop instead.

JavaScript

The following will give you the intended result:

JavaScript

The OR operator || returns the second argument if the first is falsey.


You can optimize this by mapping items by id instead of brute force searching the old array.

JavaScript
JavaScript

Stackblitz: https://stackblitz.com/edit/js-f3sw8w?file=index.js

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement