How can you clone an object in JavaScript?

There are multiple ways you can use to clone an object in JavaScript. Here are some of the ways:

1. Using Object.assign()

JavaScript
const originalObject = { key: 'value', number: 42 };
const clonedObject = Object.assign({}, originalObject);

2. Using Spread Operator (…)

JavaScript
const originalObject = { key: 'value', number: 42 };
const clonedObject = { ...originalObject };

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

JavaScript
const originalObject = { key: 'value', number: 42 };
const clonedObject = JSON.parse(JSON.stringify(originalObject));

Note: This method will not work correctly if your object contains functions, undefined, or symbols. Its also not helpful for cloning objects with circular references

4. Using Lodash Library

If you want to use a third-party library than you can use clone method of lodash library to clone your object.

JavaScript
const _ = require('lodash');
const originalObject = { key: 'value', number: 42 };
const clonedObject = _.clone(originalObject);

5. Using Object.create()

JavaScript
const originalObject = { key: 'value', number: 42 };
const clonedObject = Object.create(Object.getPrototypeOf(originalObject), Object.getOwnPropertyDescriptors(originalObject));

Leave a Reply

Your email address will not be published. Required fields are marked *