Object.assign keeps reference to original object
This question already has an answer here:
In fact this can be done in different ways:
deep=true
): function cloneObj(obj, deep=false){
var result = {};
for(key in obj){
if(deep && obj[key] instanceof Object){
if(obj[key] instanceof Array){
result[key] = [];
obj[key].forEach(function(item){
if(item instanceof Object){
result[key].push(cloneObj(item, true));
} else {
result[key].push(item);
}
});
} else {
result[key] = cloneObj(obj[key]);
}
} else {
result[key] = obj[key];
}
}
return result
}
// Shallow copy
var newObject = cloneObj(oldObject);
// Deep copy
var newObject = cloneObj(oldObject, true);
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
// Shallow copy
var newObject = _.clone(oldObject);
PS: I tested my function with the following data and works fine:
var oldObject = {a:1, b:{d:2,c:6}, c:[1,2,{t:1}]};
newObject= cloneObj(oldObject, true);
newObject['b']['d']=8;
newObject['a']=8;
newObject['c'][2]['t']=5;
console.log(oldObject)
console.log(newObject)
链接地址: http://www.djcxy.com/p/24770.html