clone object in js

Cloning Objects in JavaScript

Cloning objects is a common task in JavaScript. It allows you to create a copy of an object without modifying the original one. There are several ways to clone objects in JavaScript, and in this article, we will look at some of the most common techniques.

1. Using Object.assign()

The Object.assign() method is a built-in function that can be used to clone an object. It creates a new object and copies all enumerable own properties from one or more source objects to the target object. Here is an example:


const obj1 = {name: 'John', age: 30};
const obj2 = Object.assign({}, obj1);
console.log(obj2); // {name: 'John', age: 30}

In the above code, we first create an object named obj1 with two properties: name and age. We then use Object.assign() to create a new object named obj2 that is a clone of obj1.

2. Using the Spread Operator

The spread operator (...) can also be used to clone an object. It works by expanding an object into individual properties, which can then be added to a new object. Here is an example:


const obj1 = {name: 'John', age: 30};
const obj2 = {...obj1};
console.log(obj2); // {name: 'John', age: 30}

In the above code, we first create an object named obj1 with two properties: name and age. We then use the spread operator (...) to create a new object named obj2 that is a clone of obj1.

3. Using JSON.parse() and JSON.stringify()

The JSON.parse() and JSON.stringify() methods can also be used to clone an object. It works by first converting the object to a string using JSON.stringify(), and then converting the string back to an object using JSON.parse(). Here is an example:


const obj1 = {name: 'John', age: 30};
const obj2 = JSON.parse(JSON.stringify(obj1));
console.log(obj2); // {name: 'John', age: 30}

In the above code, we first create an object named obj1 with two properties: name and age. We then use JSON.stringify() to convert obj1 to a string, and then use JSON.parse() to convert the string back to an object named obj2 that is a clone of obj1.

Conclusion

Cloning objects in JavaScript is a common task, and there are several ways to accomplish it. The Object.assign() method, the spread operator (...), and the JSON.parse() and JSON.stringify() methods are all viable options. Choose the one that works best for your specific use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe