Home > Software engineering >  Compare and update two arrays without losing mutated data
Compare and update two arrays without losing mutated data

Time:09-03

I have an array of objects contains data of persons

const oldArr = [
    {
        id: 1,
        name: 'Alex',
    },
    {
        id: 2,
        name: 'John',
    },
    {
        id: 3,
        name: 'Jack',
    }
]

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

oldArr.map((el, index) => el.money = 20)

and the array becomes like this

...
{
   id: 2,
   name: 'John',
   money: 20
},
...

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)

const newArr = [
    {
        id: 1,
        name: 'Alex',
    },
    {
        id: 3,
        name: 'Jack',
    },
    {
        id: 4,
        name: 'Chris',
    },
]

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:

const result = [
    {
        id: 1,
        name: 'Alex',
        money: 20
    },
    {
        id: 3,
        name: 'Jack',
        money: 20
    },
    {
        id: 4,
        name: 'Chris',
    },
]

Thanks for the help.

CodePudding user response:

If I getted it clear you are just trying to iterate throw the items of array generating a new array with the property "money" added to each one.

If so the map is the best option, just assign it to a new variable and change the item before return the element like bellow.

const oldArr = [
  {
    id: 1,
    name: "Alex"
  },
  {
    id: 2,
    name: "John"
  },
  {
    id: 3,
    name: "Jack"
  }
];

const newArr = oldArr.map((el) => {
  el.money = "20";
  return el;
});

console.log(oldArr);
console.log(newArr); 

In this way you'll be able to keep both arrays.

If wasn't this, pls let me know.

CodePudding user response:

Just merge the objects:

const result = oldArr.map((person) => ({
    ...person,
    ...newArr.find((cur) => cur.id === person.id),
}));

CodePudding user response:

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.

oldArr.forEach((el) => (el.money = 20));

The following will give you the intended result:

const result = newArr.map(
  (newEl) => oldArr.find((el) => el.id === newEl.id) || newEl
);

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

const idMap = new Map();
oldArr.forEach((el) => {
  el.money = 20;
  idMap.set(el.id, el);
});
const result = newArr.map((newEl) => idMap.get(newEl.id) || newEl);

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

  • Related