Cloning a json object and changing values mutates the original object as well

前端 未结 5 993
天涯浪人
天涯浪人 2021-01-01 07:01

I was wondering why does this happen?

I have an json object stored in var myObj:

var myObj = JSON.parse(fs.readFileSync(\'json/data.json\', \'utf8\')         


        
5条回答
  •  囚心锁ツ
    2021-01-01 07:34

    You are not cloning you are just refering the same with new variable name.

    Create a new object out of existing and use it

    var modObj  = JSON.parse(JSON.stringify(myObj));
    

提交回复
热议问题