乐闻世界logo
搜索文章和话题

How do i correctly clone a javascript object

4个答案

1
2
3
4

When cloning objects in JavaScript, the objective is to create a new object with identical properties and values to the original, yet residing in a different memory location. This ensures that modifications to the new object do not affect the original, and vice versa. Below are several common methods for cloning JavaScript objects:

Shallow Clone

Object.assign()

javascript
let original = { a: 1, b: 2 }; let clone = Object.assign({}, original);

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object (here, an empty object) and returns the target object.

Spread Operator (ES6)

javascript
let original = { a: 1, b: 2 }; let clone = { ...original };

The spread operator ... allows an expression to be expanded into multiple arguments (for function calls), multiple elements (for array literals), or multiple key-value pairs (for object literals).

Both methods above are shallow clones, meaning that if a property value of the original object is an object, the clone's property value is merely a reference to the original's property value. Modifying this nested object affects both the original and the clone.

Deep Clone

JSON Method

javascript
let original = { a: 1, b: { c: 3 } }; let clone = JSON.parse(JSON.stringify(original));

This method is straightforward for deep cloning an object. However, it has limitations, such as not cloning functions, ignoring undefined values, and failing to handle objects with circular references.

Recursive Deep Clone

javascript
function deepClone(obj) { if (obj === null || typeof obj !== 'object') { return obj; } if (obj instanceof Date) { return new Date(obj.getTime()); } if (obj instanceof Array) { let arrCopy = []; obj.forEach((v, i) => arrCopy[i] = deepClone(v)); return arrCopy; } if (obj instanceof Object) { let copy = {}; Object.getOwnPropertyNames(obj).forEach(prop => { copy[prop] = deepClone(obj[prop]); }); return copy; } throw new Error('Unable to copy object!'); } let original = { a: 1, b: { c: 3 } }; let clone = deepClone(original);

This method recursively clones the object, including nested objects. As a result, the cloned object is completely independent of the original.

Library Methods

Some JavaScript libraries (such as Lodash) provide deep cloning functionality. For example, using Lodash's _.cloneDeep():

javascript
let _ = require('lodash'); let original = { a: 1, b: { c: 3 } }; let clone = _.cloneDeep(original);

This approach is convenient, as it avoids writing complex deep cloning logic and can handle more complex scenarios, such as circular references and special object types.

In summary, the choice of cloning method depends on the required cloning depth and object complexity. For simple cases, a shallow clone may suffice. When the object structure is more complex or a completely independent copy is needed, a deep clone is preferable. In practice, we typically prefer using mature library methods to handle these tasks, reducing bugs and improving development efficiency.

2024年6月29日 12:07 回复

According to MDN:

  • For a shallow copy, use Object.assign({}, a)
  • For a deep copy, use JSON.parse(JSON.stringify(a))

No external libraries are needed, but you should first check browser compatibility. Check browser compatibility here.

2024年6月29日 12:07 回复

Use jQuery.extend for shallow copying:

javascript
var copiedObject = jQuery.extend({}, originalObject);

Subsequent changes to copiedObject will not affect originalObject, and vice versa.

Alternatively, for deep copying:

javascript
var copiedObject = jQuery.extend(true, {}, originalObject);
2024年6月29日 12:07 回复

In ECMAScript 6, there is an Object.assign method that copies all enumerable own property values from one object to another. For example:

javascript
var x = {myProp: "value"}; var y = Object.assign({}, x);

However, note that this is a shallow copy – nested objects are still copied by reference.

2024年6月29日 12:07 回复

你的答案