How to Create a Copy of an Object ?
In JavaScript, there are several methods to create a copy of an object, each with its own characteristics:
Table of Content
- Using Object.assign()
- Using the Spread Syntax (…)
- Using JSON.parse() and JSON.stringify() for Deep Cloning
- Using Libraries like Lodash for Cloning
Using Object.assign()
In this Object.assign() is used to assign the values of the previously existing object into the new object.
const originalObject = { a: 1, b: { c: 2 } };
const clonedObject = Object.assign({}, originalObject);
Using the Spread Syntax (…)
In this approach, spread operator is used to make a copy of an object.
const originalObject = { a: 1, b: { c: 2 } };
const clonedObject = { ...originalObject };
Using JSON.parse() and JSON.stringify() for Deep Cloning
In this approach, we are using json.parse() and json.stringify() method for cloning the object.
const originalObject = { a: 1, b: { c: 2 } };
const clonedObject = JSON.parse(JSON.stringify(originalObject));
Using Lodash
In this approach, we are using Lodash library for cloning the object. as lodash provides a lot of methods that can be used to create a copy of the object.
const originalObject = { a: 1, b: { c: 2 } };
// Requires lodash library
const clonedObject = _.cloneDeep(originalObject);