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?

2
  • There is no all property in the data you have shown? Commented Aug 15, 2019 at 20:36
  • return Object.assign({}, newData[key], { all: newData[key].all * 2 }) from within the .map. Commented Aug 15, 2019 at 20:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

map is array method, not available on objects.
@Clarity According to OP, oldData should be an array.
I only see rawData there.
@Clarity Same thing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.