The structuredClone
method allows you to deep clone a object including its keys and values.
const person = {
name: 'Paul G. Reynolds',
skills: ['javascript','react','ember','vue']
dob: new Date('1995-11-25')
}
const person2 = structuredClone(person);
person2.name = 'Brad T. Kennedy';
console.log(person.name); //Paul G. Reynolds
console.log(person2.name); //Brad T. Kennedy
As you see in the above code altering person2.name
did not alter person.name
.
You might think we can achieve this by using javascript spread operator.
const person2 = {
...person
}
But, the problem is skills
is an array altering person2.skills
will alter person.skills
too.
In such case you can think we can also use,
person2 = JSON.parse(JSON.stringify(person))
//{"name":"Paul G. Reynolds","skills":["javascript","react","ember","vue"],"dob":"1995-11-25T00:00:00.000Z"}
Here the problem is dob
is a Date object it will loose it's properties and become string value.
Previously we need to use lot of workarounds like this to achieve deep cloning now we have a built in method structuredClone
.
One thing to keep in mind when using structuredClone
is, that it only works on structured objects. If you try to clone an unstructured object, you will get an error. For example:
const func = () => {
console.log('Hello, world!');
};
const func2 = structuredClone(func); // Error!
In this example, we tried to clone a function object using structuredClone
method, but it will raise an error because functions are not structured objects.
Supported browsers
Chrome | Edge | Firefox | Safari |
---|---|---|---|
98 | 98 | 94 | 15.4 |
Source: MDN
Conclusion
The structuredClone
method in JavaScript is a powerful tool for making exact copies of objects.
If you read until the end leave a like and share your thoughts in the comment section
Checkout full spec: MDN StructuredClone
Names generated from https://www.fakenamegenerator.com/
Top comments (0)