1

I have an object array that looks like this:

rawData:
0: {name: "cat", count: 2}
1: {name: "dog", count: 5}
2: {name: "fish", count: 3}

and I have a translatedData that multiplies the count field by 2.

newData:
0: {name: "cat", count: 4}
1: {name: "dog", count: 10}
2: {name: "fish", count: 6}

I use the following calculation:

let newData = Object.assign({}, rawData);

newData = Object.keys(newData).map(key => {
  let newValue = Math.round(newData[key].all*2);
  newData[key].all = newValue;
  return newData[key];
});

I use a map to perform this calculation. My issue is when when I console.log both these arrays they both have the calculation. I want the rawData to have its previous state and not be affected by the calculation.I thought object.assign would fix this. What am i doing wrong?

lost9123193
  • 10,460
  • 26
  • 73
  • 113

1 Answers1

0

As stated in the comment, the problem is you haven't performed a deep clone. You could go that route, but a simpler (and more typical) solution is to just construct the new object manually, in the map call.

newData = rawData.map(({name, count}) => ({name, count: count * 2})

If the data is actually highly nested and this is just an simplified example, the deep clone option might be better.

The above is assuming your object is an Array.