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

前端 未结 5 1151
天涯浪人
天涯浪人 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条回答
  •  Happy的楠姐
    2021-01-01 07:30

    You are not cloning ! :/

    Replace this:

    var modObj = myObj;
    

    By this:

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

    If myObj is an array do this:

    var modObj = myObj.slice();
    

提交回复
热议问题