我有一个对象x。我想将其复制为对象y,这样对y的更改不会修改x。我意识到复制从内置JavaScript对象派生的对象会导致额外的、不需要的财产。这不是问题,因为我正在复制我自己的一个文字构造对象。
如何正确克隆JavaScript对象?
我有一个对象x。我想将其复制为对象y,这样对y的更改不会修改x。我意识到复制从内置JavaScript对象派生的对象会导致额外的、不需要的财产。这不是问题,因为我正在复制我自己的一个文字构造对象。
如何正确克隆JavaScript对象?
当前回答
我已经编写了自己的实现。不确定它是否算作更好的解决方案:
/*
a function for deep cloning objects that contains other nested objects and circular structures.
objects are stored in a 3D array, according to their length (number of properties) and their depth in the original object.
index (z)
|
|
|
|
|
| depth (x)
|_ _ _ _ _ _ _ _ _ _ _ _
/_/_/_/_/_/_/_/_/_/
/_/_/_/_/_/_/_/_/_/
/_/_/_/_/_/_/...../
/................./
/..... /
/ /
/------------------
object length (y) /
*/
实施情况如下:
function deepClone(obj) {
var depth = -1;
var arr = [];
return clone(obj, arr, depth);
}
/**
*
* @param obj source object
* @param arr 3D array to store the references to objects
* @param depth depth of the current object relative to the passed 'obj'
* @returns {*}
*/
function clone(obj, arr, depth){
if (typeof obj !== "object") {
return obj;
}
var length = Object.keys(obj).length; // native method to get the number of properties in 'obj'
var result = Object.create(Object.getPrototypeOf(obj)); // inherit the prototype of the original object
if(result instanceof Array){
result.length = length;
}
depth++; // depth is increased because we entered an object here
arr[depth] = []; // this is the x-axis, each index here is the depth
arr[depth][length] = []; // this is the y-axis, each index is the length of the object (aka number of props)
// start the depth at current and go down, cyclic structures won't form on depths more than the current one
for(var x = depth; x >= 0; x--){
// loop only if the array at this depth and length already have elements
if(arr[x][length]){
for(var index = 0; index < arr[x][length].length; index++){
if(obj === arr[x][length][index]){
return obj;
}
}
}
}
arr[depth][length].push(obj); // store the object in the array at the current depth and length
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) result[prop] = clone(obj[prop], arr, depth);
}
return result;
}
其他回答
在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
使用扩展语法执行对象的浅层复制。这意味着没有任何嵌套对象实例被克隆,正如您在下面的嵌套对象子实例示例中看到的那样
常量user1={name:“Alex”,地址:'公园大道15号',年龄43岁,儿童:{name:“John”}}const user2={…user1};user1.child.name='chris';console.log(用户1);console.log(用户2);
为了解决这个嵌套对象问题并执行深度复制,我们可以使用JSON.parse(JSON.stringify(someObject))
常量user1={name:“Alex”,地址:'公园大道15号',年龄43岁,儿童:{name:“John”}}const user2=JSON.parse(JSON.stringify(user1));user1.child.name='chris';console.log(用户1);console.log(用户2);
使用(…)复制对象
//bad
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2,c: 3 }
//good
const originalObj = { id: 5, name: 'San Francisco'};
const copyObject = {...originalObj, pincode: 4444};
console.log(copyObject) //{ id: 5, name: 'San Francisco', pincode: 4444 }
同样可以用于将阵列从一个复制到另一个
const itemsCopy = [...items];
克隆对象的简单递归方法。也可以使用lodash.clone。
让克隆=(obj)=>{let obj2=Array.isArray(obj)?[] : {};for(设k为obj){obj2[k]=(obj[k]===“对象”的类型)?克隆(obj[k]):obj[k];}返回obj2;}让w={name:“Apple”,类型:[“Fuji”,“Gala”]};设x=克隆(w);w.name=“橙色”;w.types=[“Navel”];console.log(x);console.log(w);