Cloning A Json Object And Changing Values Mutates The Original Object As Well
Solution 1:
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));
Solution 2:
You are not cloning, you are just passing the reference to myObj
to modObj
.
You can use Object.assign()
var modObj = Object.assign({},myObj);
The
Object.assign()
method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Solution 3:
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();
Solution 4:
If you use jQuery, then you can do this
var mobObj = jQuery.extend(true, {}, myObj);
else try this
var mobObj = Object.assign({}, myObj);
Solution 5:
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:
functionclone(deep, obj=undefined){
var fn = clone[deep? "deep": "shallow"] || function(obj){
return (!obj || typeof obj !== "object")? obj: //primitivesArray.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 objectObject.assign({}, obj);
};
return obj === undefined? fn: fn(obj);
}
clone.deep = clone(true);
clone.shallow = clone(false);
and then
//make a deep copyvar modObj = clone.deep(myObj);
//or var modObj = clone(true, myObj);
//or a shallow onevar modObj = clone.shallow(myObj);
//orvar modObj = clone(false, myObj);
I prefer this style clone.deep(whatever)
because the code is self explaining and easy to scan over.
Post a Comment for "Cloning A Json Object And Changing Values Mutates The Original Object As Well"