0

I tried copying a JSON variable to another variable and then deleting part of the content of the second variable, however the content from the first variable was also deleted.
How can I make it that I delete the part of the second variable but not the part from the first variable?
Thank you for every help!!

var variable1 = {
  test1 : "test1",
  test2 : "test2"
}

var variable2 = variable1;

variable2.test1 = "";

console.log(JSON.stringify(variable1));
console.log(JSON.stringify(variable2));
Aniket Kolekar
  • 383
  • 6
  • 19
  • 4
    Does this answer your question? [How do I correctly clone a JavaScript object?](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object). Side note: That's not a "JSON Variable". It's a plain old JavaScript Object. – NullDev Jun 08 '21 at 13:42
  • JSON is a string representation of data. The only JSON in your example is when you stringify the JavaScript objects in `variable1` and `variable2` – crashmstr Jun 08 '21 at 13:43
  • While it is a duplicate, the answer over there is not really useful. 1: you arent using JSON, but an object. 2: do `variable2 = {...variable1}`. The ... is the spread operator and you can read all about it here: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Spread_syntax – DownloadPizza Jun 08 '21 at 13:45
  • 1
    Ironically, going via JSON would be a valid (albeit inefficient) way of cloning the object: `const variable2 = JSON.parse(JSON.stringify(variable1))` – Niet the Dark Absol Jun 08 '21 at 13:45
  • 1
    @DownloadPizza That's a shallow copy, which is sufficient in this example but will cause issues if there are nested objects. – Niet the Dark Absol Jun 08 '21 at 13:45

1 Answers1

-2

var variable1 = {
  test1 : "test1",
  test2 : "test2"
}

var variable2 = {... variable1};

variable2.test1 = "";

console.log(JSON.stringify(variable1));
console.log(JSON.stringify(variable2));
Hamada
  • 1,836
  • 3
  • 13
  • 27