我有一个对象x。我想将其复制为对象y,这样对y的更改不会修改x。我意识到复制从内置JavaScript对象派生的对象会导致额外的、不需要的财产。这不是问题,因为我正在复制我自己的一个文字构造对象。
如何正确克隆JavaScript对象?
我有一个对象x。我想将其复制为对象y,这样对y的更改不会修改x。我意识到复制从内置JavaScript对象派生的对象会导致额外的、不需要的财产。这不是问题,因为我正在复制我自己的一个文字构造对象。
如何正确克隆JavaScript对象?
当前回答
对于深度复制和克隆,JSON.stringify然后JSON.parse对象:
obj = { a: 0 , b: { c: 0}};
let deepClone = JSON.parse(JSON.stringify(obj));
obj.a = 5;
obj.b.c = 5;
console.log(JSON.stringify(deepClone)); // { a: 0, b: { c: 0}}
其他回答
可以使用rest运算符克隆阵列或对象
let myObj = {1: 100, 'a': 200};
let clone = {...myObj};
clone.a = 300;
console.log(clone.a) // Output :- 300
console.log(myObj.a) // Output :- 200
我为这个问题提供了答案,因为我在这里没有看到任何解决DOM元素问题的本地递归实现。
问题是<element>具有父属性和子属性,这些属性链接到具有父值和子值的其他元素,这些元素指向原始<element>,从而导致无限递归或循环冗余。
如果你的目标是安全简单的
{
'123':456
}
……那么这里的任何其他答案都可能奏效。
但如果你有。。。
{
'123':<reactJSComponent>,
'456':document.createElement('div'),
}
…那么你需要这样的东西:
// cloneVariable() : Clone variable, return null for elements or components.
var cloneVariable = function (args) {
const variable = args.variable;
if(variable === null) {
return null;
}
if(typeof(variable) === 'object') {
if(variable instanceof HTMLElement || variable.nodeType > 0) {
return null;
}
if(Array.isArray(variable)) {
var arrayclone = [];
variable.forEach((element) => {
arrayclone.push(cloneVariable({'variable':element}));
});
return arrayclone;
}
var objectclone = {};
Object.keys(variable).forEach((field) => {
objectclone[field] = cloneVariable({'variable':variable[field]});
});
return objectclone;
}
return variable;
}
在ES-6中,您可以简单地使用Object.assign(…)。前任:
let obj = {person: 'Thor Odinson'};
let clone = Object.assign({}, obj);
这里有一个很好的参考:https://googlechrome.github.io/samples/object-assign-es6/
您可以在不修改父对象的情况下克隆对象-
/** [Object Extend]*/
( typeof Object.extend === 'function' ? undefined : ( Object.extend = function ( destination, source ) {
for ( var property in source )
destination[property] = source[property];
return destination;
} ) );
/** [/Object Extend]*/
/** [Object clone]*/
( typeof Object.clone === 'function' ? undefined : ( Object.clone = function ( object ) {
return this.extend( {}, object );
} ) );
/** [/Object clone]*/
let myObj = {
a:1, b:2, c:3, d:{
a:1, b:2, c:3
}
};
let clone = Object.clone( myObj );
clone.a = 10;
console.log('clone.a==>', clone.a); //==> 10
console.log('myObj.a==>', myObj.a); //==> 1 // object not modified here
let clone2 = Object.clone( clone );
clone2.a = 20;
console.log('clone2.a==>', clone2.a); //==> 20
console.log('clone.a==>', clone.a); //==> 10 // object not modified here
好的,假设你有下面的这个对象,你想克隆它:
let obj = {a:1, b:2, c:3}; //ES6
or
var obj = {a:1, b:2, c:3}; //ES5
答案主要取决于您使用的ECMAscript,在ES6+中,您可以简单地使用Object.assign来执行克隆:
let cloned = Object.assign({}, obj); //new {a:1, b:2, c:3};
或使用如下扩展运算符:
let cloned = {...obj}; //new {a:1, b:2, c:3};
但是如果你使用ES5,你可以使用很少的方法,但JSON.stringify,只需确保你没有使用大量数据来复制,但在很多情况下,这可能是一种简单的方法,比如:
let cloned = JSON.parse(JSON.stringify(obj));
//new {a:1, b:2, c:3};, can be handy, but avoid using on big chunk of data over and over