How to Clone a JavaScript object – Example

To correctly clone a JavaScript object, you can use the Object.assign() method to create a new object with the properties of the original object. Here’s an example:

const originalObject = {a: 1, b: 2, c: 3};
// Create a new object with the properties of the original object
const clonedObject = Object.assign({}, originalObject);

// Modify a property on the cloned object
clonedObject.a = 10;

console.log(originalObject); // {a: 1, b: 2, c: 3}
console.log(clonedObject); // {a: 10, b: 2, c: 3}

Keep in mind that Object.assign() creates a shallow copy of the object, meaning that any nested objects or arrays will be copied by reference instead of by value. To create a deep clone of an object, you’ll need to use a different approach.

Whereas, to create a deep clone of an object in JavaScript, you can use the JSON.parse() and JSON.stringify() methods to serialize and deserialize the object. This will create a new object with copies of the original object’s properties, as well as any nested objects or arrays. Here’s an example:

const originalObject = {
a: 1,
b: 2,
c: {
d: 3,
e: 4
}
};

// Serialize the object to a JSON string
const serializedObject = JSON.stringify(originalObject);

// Deserialize the JSON string to create a new object
const clonedObject = JSON.parse(serializedObject);

// Modify a property on the original object
originalObject.c.d = 10;

console.log(originalObject); // {a: 1, b: 2, c: {d: 10, e: 4}}
console.log(clonedObject); // {a: 1, b: 2, c: {d: 3, e: 4}}

This approach will create a deep clone of the object, including any nested objects or arrays. However,  this approach will not work for objects that have circular references, since the JSON.stringify() method cannot serialize circular references.

1 thought on “How to Clone a JavaScript object – Example”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.