Different ways to clone object
without using third-party libraries.
Using Spread Operator
:
const example = {first: 1, last: 10};
const {...clonedExample} = example;
clonedExample
> {first: 1, last: 10}
clonedExample.first = 2;
> 2
clonedExample
> {first: 2, last: 10}
example
> {first: 1, last: 10}
Using Object.assign()
;
const example = {first: 1, last: 10};
const clonedExample = Object.assign({}, example);
clonedExample
> {first: 1, last: 10}
clonedExample.first = 2;
> 2
clonedExample
> {first: 2, last: 10}
example
> {first: 1, last: 10}
Using JSON.parse
:
const example = {first: 1, last: 10};
const clonedExample = JSON.parse(JSON.stringify(example));
clonedExample
> {first: 1, last: 10}
clonedExample.first = 2;
> 2
clonedExample
> {first: 2, last: 10}
example
> {first: 1, last: 10}
In above methods, first two can't achieve deep cloning of objects. Only first hand objects muted not the nested objects whereas deep cloning achieved only using JSON.parse
.
see below example:
const example = {first: 1, last: {nested: 3}};
// Using Spread
const {...clonedExample} = example;
clonedExample.last.nested = 5;
> 5
clonedExample
> {first: 1, last: {nested: 5}}
example
> {first: 1, last: {nested: 5}}
// Using Object.assign
const clonedExample = Object.assign({}, example);
clonedExample.last.nested = 5;
> 5
clonedExample
> {first: 1, last: {nested: 5}}
example
> {first: 1, last: {nested: 5}}
// Using JSON.parse
const clonedExample = JSON.parse(JSON.stringify(example));
clonedExample.last.nested = 5;
> 5
clonedExample
> {first: 1, last: {nested: 5}}
example
> {first: 1, last: {nested: 3}}
You can follow me here: https://twitter.com/urstrulyvishwak
Thanks.
Oldest comments (4)
use structuredClone
Good. One thanks.
It is important to point out that the use of Object.assign must be done with care as it can open a gap for attacks like Prototype Pollution. Ideally, when using this method, make sure that the data of the object to be cloned has already been properly sanitized.
But it was a good tip anyway, for those new to javascript it's good to know how to do what 😀
JSON.stringify will fail on Symbols and recursive structures. If you only need shallow cloning,
Object.assign
or the spread operator will work fine, otherwise consider the newstructuredClone(obj)
, which is available in all modern browsers (a polyfill is available: github.com/ungap/structured-clone).