-3

I was trying to copy the contents of a particular JSON to another JSON and modify the temporary variable to my needs but the original JSON is also getting changed.

For example :

count = {
    passed : 2,
    failed : 5
} 
console.log(count)   // logs the JSON content
let temp = count;
console.log(temp)   // logs the JSON content

Say, now I'm modifying the temp, like :

temp.passed = 0;
console.log(temp);   //{passed : 0, failed : 5}

It is also changing the passed value of count too. Now if I log JSON of count,

console.log(count);    //{passed : 0, failed : 5}

where I want the passed to be 2, since I only modified the JSON object of passed in temp.

I want to keep the count to be same and modify only the temp. Can someone help me out ?

9094SS
  • 9

2 Answers2

1

First, that is not JSON, that is an "object literal". They are different things.

You need to clone the object, such as with a destructuring assignment:

count = {
  passed: 2,
  failed: 5
}

const temp = { ...count };

temp.passed = 0;

console.dir(temp);
console.dir(count);

Or with Object.assign() and an empty object, proposed by Kenry.

msanford
  • 11,803
  • 11
  • 66
  • 93
1

You must clone your object to add more properties and don't change the source.

Use Object.assign()

let temp = Object.assign({}, count);

In this way, you can add more properties without change the source.

Kenry Sanchez
  • 1,703
  • 2
  • 18
  • 24