You can use structuredClone()
like the following:
const myOriginal = {
title: "Full Stack JavaScript Developer",
info: {
firstname: "Javascript",
surname: " Addicted",
age: 34
}
};
const myDeepCopy = structuredClone(myOriginal);
structuredClone()
You can use structuredClone()
that is a built-in function for deep-copying.
Structured cloning addresses many (although not all) shortcomings of the JSON.stringify()
technique.
Structured cloning can handle cyclical data structures,
support many built-in data types, and is generally more robust and often faster.
However, it still has some limitations that may catch you off-guard:
1-Prototypes : If you use structuredClone()
with a class instance,
you’ll get a plain object as the return value, as structured cloning discards the object’s prototype chain.
2-Functions: If your object contains functions, they will be quietly discarded.
3- Non-cloneables: Some values are not structured cloneable, most notably Error and DOM nodes. It will cause structuredClone() to throw.
const myDeepCopy = structuredClone(myOriginal);
JSON.stringify
If you simply want to deep copy the object to another object,
all you will need to do is JSON.stringify
the object and parse it using JSON.parse
afterward.
This will essentially perform deep copying of the object.
let user1 = {
name: 'Javascript Addicted',
age: 34,
university: {
name: 'Shiraz Bahonar University'
}
};
let user2 = JSON.parse(JSON.stringify(user1));
user2.name = 'Andy Madadian';
user2.university.name = 'Kerman Bahonar University'
console.log(user2);
// { name: 'Andy Madadian', age: 33, university: { name: 'Kerman Bahonar University' } }
console.log(user1);
// { name: 'Javascript Addicted', age: 33, university: { name: 'Shiraz Bahonar University' } }
Spread operator / Object.assign()
One way to create a shallow copy in JavaScript using the object spread operator ... or Object.assign()
like the following:
const myShallowCopySpread = {...myOriginal};
const myShallowCopyObjectAssign=Object.assign({},obj)
Performance
When it comes to performance the creator Surma has pointed out that JSON.Parse()
can be a bit faster for small objects. But when you have a large object, complex object
structuredClone()
starts to get significantly faster.
Browser support is pretty fantastic And even is supported by Node.js.
combineReducers
to compose the two (or more) together. If you use idiomatic redux techniques, your problem of deep cloning objects goes away. – Rimple