How to clone javascript object ?
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 resultWe 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 👏
