Asked 1 years ago
24 Apr 2023
Views 262
pratik

pratik posted

how to clone an object in JavaScript?

how to make a simple or complex object with nested object in JavaScript
Rasi

Rasi
answered May 1 '23 00:00

In JavaScript, you can clone an object using several methods , depending on your requirements.

Using the spread operator (...) : This method is the simplest and most concise way to clone an object. It creates a shallow copy of the object, meaning that nested objects and arrays will still reference the same memory locations as the original object.


const original = { a: 1, b: 2 };
const clone = { ...original };
console.log(clone); // Output: { a: 1, b: 2 }



Using Object.assign() : This method also creates a shallow copy of the object, and can be used to clone an object with additional properties.

const original = { a: 1, b: 2 };
const clone = Object.assign({}, original);
console.log(clone); // Output: { a: 1, b: 2 }



Using JSON.parse() and JSON.stringify() : This method creates a deep copy of the object, meaning that all nested objects and arrays are also cloned. However, it has some limitations - it can only clone objects that can be serialized to JSON, and it can't clone functions or undefined values.


const original = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(original));
console.log(clone); // Output: { a: 1, b: { c: 2 } }

It's important to note that while these methods can clone objects, they can't clone object prototypes or functions. If you need to clone these properties as well, you may need to use a more complex method, such as deep cloning with recursion or using a third-party library like lodash.
Post Answer