clone object in javascript

There are several ways to clone an object in JavaScript. One way to do this is by using the spread operator. Here is an example:

index.tsx
const myObj = {name: 'John', age: 30};
const clonedObj = {...myObj};
console.log(clonedObj); // output: {name: 'John', age: 30}
128 chars
4 lines

In the above example, we first define an object myObj with some key-value pairs. We then create a clonedObj by using the spread operator .... This creates a new object with the same values as myObj. We then log the clonedObj to the console and see that it prints the same values as myObj.

Another way to clone an object in JavaScript is by using the Object.assign() method. Here is an example:

index.tsx
const myObj = {name: 'John', age: 30};
const clonedObj = Object.assign({}, myObj);
console.log(clonedObj); // output: {name: 'John', age: 30}
142 chars
4 lines

In the above example, we first define the myObj object. We then create a clonedObj by using the Object.assign() method. This creates a new object with the same values as myObj. We then log the clonedObj to the console and see that it prints the same values as myObj.

gistlibby LogSnag