-1

I have an existing JSON and I take part of the JSON and modify it by creating a new JSON. Now, when I do a console.log of the existing JSON, it shows the existing JSON to have the updates done on the new JSON. Why is that happening ? (I'm doing this in React)

var newJSON = [];
let ifruleObject = oldJSON.rules[0].rules;
console.log(oldJSON);

ifruleObject.forEach((e) => {
for( var i=0; i<ifruleObject.length; i++)
 {
   if(ifruleObject[i].length <= 3)
    {
        ifruleObject[i]={ruleid:ifruleObject[i-1].id, rulecombinator: ifruleObject[i]}; 
        newJSON .push(ifruleObject[i]);
    }
 }
});

console.log(newJSON);
Kay
  • 57
  • 1
  • 7
  • 1
    ifruleObject is a reference to the original object.`ifruleObject[i]={ruleid:ifruleObject[i-1].id, rulecombinator: ifruleObject[i]};` you are reassaignin the value here. Instead create a temporari value `let temp ={ruleid:ifruleObject[i-1].id, rulecombinator: ifruleObject[i]}; newJSON .push(temp);` – Marko Taht Feb 08 '23 at 19:59
  • 1
    Please read the tag description before you use a tag. The JSON tag contains: _"Do not use this tag for native JavaScript objects or JavaScript object literals."_ There is no JSON in your question. – jabaa Feb 08 '23 at 20:12
  • 2
    @kay - reference jabaa's comment. Perhaps read this: "_JSON exists as a string_" from [No, really, what is JSON?](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON#no_really_what_is_json) – Randy Casburn Feb 08 '23 at 20:15
  • Could you fix the code snippet to reproduce the problem. Currently, I'm getting `"SyntaxError: missing } after function body"`. Don't use unrelated tags. Your question is unrelated to React. – jabaa Feb 08 '23 at 20:15

1 Answers1

0

In JS, objects store references. That means, if you assign an object to another variable, any changes made to that other variable will change the original object.

let obj = {a: 10, b: 20};
let copy = obj;
copy.a = 20;
console.log(obj);
console.log(copy);

In your code, you are storing the oldJSON.rules[0].rules object to ifruleObject. ifruleObject now references the original object at oldJSON.rules[0].rules. When you change ifruleObject[i], you are changing the oldJSON object implicitly (see above snippet).

You need to create a new object, copy the elements from the old object, and then assign the new object to your new object. Here is a possible implementation:

let temp = {ruleid: ifruleObject[i-1].id, rulecombinator: {...ifruleObject[i]}};
newJSON.push(temp);
2pichar
  • 1,348
  • 4
  • 17