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

前端 未结 5 1158
天涯浪人
天涯浪人 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:35

    although JSON.parse(JSON.stringify(myObj)) may seem simple and tempting, especially for bigger data structures it is not, because it has to serialize the objects and then parse this string again. I'd reccomend something like this:

    function clone(deep, obj=undefined){
        var fn = clone[deep? "deep": "shallow"] || function(obj){
            return (!obj || typeof obj !== "object")? obj:  //primitives
                Array.isArray(obj)? obj.map(fn):            //real arrays
                deep? 
                    //make a deep copy of each value, and assign it to a new object;
                    Object.keys(obj).reduce((acc, key) => (acc[key] = fn(obj[key]), acc), {}):
                    //shallow copy of the object
                    Object.assign({}, obj);
        };
        return obj === undefined? fn: fn(obj);
    }
    clone.deep = clone(true);
    clone.shallow = clone(false);
    

    and then

    //make a deep copy
    var modObj = clone.deep(myObj);
    //or 
    var modObj = clone(true, myObj);
    
    //or a shallow one
    var modObj = clone.shallow(myObj);
    //or
    var modObj = clone(false, myObj);
    

    I prefer this style clone.deep(whatever) because the code is self explaining and easy to scan over.

提交回复
热议问题