How to clone javascript object ?

Vivek Gautam
Nov 7 · 2 min read

There is always a question, how to copy one JS object to another leaving behind specific key. Lets discuss how we can clone by just using arrow function.

const myObject = {
a: 1,
b: 2,
c: 3,
d: 4
};
const newObject = ((({
a,
...restKeys
}) => restKeys)(myObject))
// newObject will have all the keys except a

We can also do the same in a more readable format 😎.

let myObject = {
a: 1,
b: 2,
c: 50,
leaveMeBehindKey: 1000
};
let {
leaveMeBehindKey,
...newObject
} = myObject;

What if we have to remove nested object key 😨.

let myObject = {
a: 1,
b: 2,
c: 50,
leaveMeBehindNestedKey: {
key1: '60',
key2: '70'
}
};
let {
leaveMeBehindNestedKey,
...newObject
} = myObject;

Let’s say we want to remove move than 1 key ,for that just simply add all keys in the list.

let myObject = {
a: 1,
b: 2,
c: 50,
leaveMeBehindNestedKey1: {
key1: '60',
key2: '70'
},
leaveMeBehindNestedKey2: {
key1: '60',
key2: '70'
}
};
let {
leaveMeBehindNestedKey1,
leaveMeBehindNestedKey2,
...newObject
} = myObject;

How about using Object.assign ?

let myObject = {
a: 1,
b: 2,
c: 50,
leaveMeBehindNestedKey1: {
key1: '60',
key2: '70'
},
leaveMeBehindNestedKey2: {
key1: '60',
key2: '70'
}
};
let newObject = Object.assign({}, myObject);
delete newObject.leaveMeBehindNestedKey1;
delete newObject.leaveMeBehindNestedKey1;
// newObject will contain the same result

We can also create your own array of keys to remove and then can create array of keys to keep. After that we can simply map through arrayOfKeysToKeep and copying the keys from originalObj.

const myObject = {
a: 1,
b: 2,
c: 3,
d: 4
};
const arrayOfKeysToRemove = ['c', 'd'];const arrayOfKeysToKeep = Object.keys(myObject).filter((key) => !arrayOfKeysToRemove.includes(key));const newObj = {};arrayOfKeysToKeep.map((key) => {
newObj[key] = myObject[key];
});

I know the list is not yet completed , Let me know if there are other topics to be included . Don’t forget to clap 👏

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade