DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

Clone an object or array (Shallow Cloning)

Note: This method is for shallow cloning.

const obj = {
  name: 'xyz',
  age: 20
};

const objCopy = obj; // objCopy would still point to the same object.
// i.e., If obj.age is changed (obj.age = 35;),  
// objCopy.age will also be 35

// To clone the object,
// Solution 1 - Use the spread operator. 
const objCopy = {...obj};

// Solution 2 - Object.assign() 
const objCopy = Object.assign({}, obj);
Enter fullscreen mode Exit fullscreen mode

Thanks for reading 💙

Follow @codedrops.tech for daily posts.

InstagramTwitterFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript

codedrops.tech

Top comments (1)

Collapse
 
ml318097 profile image
Mehul Lakhanpal

Oh yes, I forgot to mention its shallow cloning. I have a post on Deep cloning too.
Thanks