The ways to correctly clone a JavaScript object
Here are the ways to correctly clone a JavaScript object:
1. Using the Object.assign()
method
const original = { a: 1, b: 2, c: 3 };
const clone = Object.assign({}, original);
This method creates a new object and copies the properties from the original object to the new object.
2. Using the spread operator ({...}
)
const original = { a: 1, b: 2, c: 3 };
const clone = {...original };
This method creates a new object and copies the properties from the original object to the new object.
3. Using JSON.parse()
and JSON.stringify()
const original = { a: 1, b: 2, c: 3 };
const clone = JSON.parse(JSON.stringify(original));
This method converts the original object to a JSON string, and then parses the string back into a new object.
4. Using a library like Lodash
const _ = require('lodash');
const original = { a: 1, b: 2, c: 3 };
const clone = _.cloneDeep(original);
This method uses the cloneDeep
function from Lodash to create a deep copy of the original object.
5. Using a recursive function
function clone(obj) {
if (typeof obj!== 'object') return obj;
const clone = Array.isArray(obj)? [] : {};
for (const key in obj) {
clone[key] = clone(obj[key]);
}
return clone;
}
const original = { a: 1, b: 2, c: 3 };
const clone = clone(original);
This method uses a recursive function to create a deep copy of the original object.
6. Using the structuredClone()
function (ECMAScript 2022)
const original = { a: 1, b: 2, c: 3 };
const clone = structuredClone(original);
This method creates a deep copy of the original object using the structuredClone
function, which is a new feature in ECMAScript 2022.
Latest blog posts
Explore the world of programming and cybersecurity through our curated collection of blog posts. From cutting-edge coding trends to the latest cyber threats and defense strategies, we've got you covered.