This content originally appeared on DEV Community 👩💻👨💻 and was authored by Mahesh
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.
This content originally appeared on DEV Community 👩💻👨💻 and was authored by Mahesh
Mahesh | Sciencx (2022-09-11T16:20:19+00:00) Javascript: Clone object. Retrieved from https://www.scien.cx/2022/09/11/javascript-clone-object/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.