Sunday, September 11, 2022
HomeWordPress DevelopmentJavascript: Clone object - DEV Group 👩‍💻👨‍💻

Javascript: Clone object – DEV Group 👩‍💻👨‍💻


Other ways to clone object with out utilizing third-party libraries.

Utilizing Unfold Operator:

const instance = {first: 1, final: 10};

const {...clonedExample} = instance;

clonedExample
> {first: 1, final: 10}

clonedExample.first = 2;
> 2

clonedExample
> {first: 2, final: 10}

instance
> {first: 1, final: 10}

Enter fullscreen mode

Exit fullscreen mode

Utilizing Object.assign();


const instance = {first: 1, final: 10};
const clonedExample = Object.assign({}, instance);

clonedExample
> {first: 1, final: 10}

clonedExample.first = 2;
> 2

clonedExample
> {first: 2, final: 10}

instance
> {first: 1, final: 10}

Enter fullscreen mode

Exit fullscreen mode

Utilizing JSON.parse:

const instance = {first: 1, final: 10};
const clonedExample = JSON.parse(JSON.stringify(instance));

clonedExample
> {first: 1, final: 10}

clonedExample.first = 2;
> 2

clonedExample
> {first: 2, final: 10}

instance
> {first: 1, final: 10}

Enter fullscreen mode

Exit fullscreen mode

In above strategies, first two cannot obtain deep cloning of objects. Solely first hand objects muted not the nested objects whereas deep cloning achieved solely utilizing JSON.parse.

see beneath instance:

const instance = {first: 1, final: {nested: 3}};

// Utilizing Unfold
const {...clonedExample} = instance;

clonedExample.final.nested = 5;
> 5

clonedExample
> {first: 1, final: {nested: 5}}

instance
> {first: 1, final: {nested: 5}}

// Utilizing Object.assign
const clonedExample = Object.assign({}, instance);

clonedExample.final.nested = 5;
> 5

clonedExample
> {first: 1, final: {nested: 5}}

instance
> {first: 1, final: {nested: 5}}

// Utilizing JSON.parse
const clonedExample = JSON.parse(JSON.stringify(instance));

clonedExample.final.nested = 5;
> 5

clonedExample
> {first: 1, final: {nested: 5}}

instance
> {first: 1, final: {nested: 3}}

Enter fullscreen mode

Exit fullscreen mode

You may observe me right here: https://twitter.com/urstrulyvishwak

Thanks.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments