How to make a deep copy of an object properties specified in array. For instance i have an object {a: 1, b: 2, c: 3} And an array ["a", "b"]. I want to deeply clone only the specified properties in object, so i need to get something like this {a: 1, b: 2}. Is there an easy way to do that?
3 Answers
// By defining Keys as keys of T, you get autocompletion
// Also by setting mapped type as return you only get
// the props you have copied in the return
const getSubset = <T, Keys extends keyof T, SubSet extends { [K in Keys]: T[K] }>(
obj: T,
keys: Keys[]
): SubSet => {
return keys.reduce((acc, key) => ({ [key]: obj[key], ...acc }), <SubSet>{});
};
const object = { bio: { name: "James", age: 23 }, hobbies: ["Fishing", "Hunting", "Coding"] };
// now copy will only show you bio and not hobbies
const copy = getSubset(object, ["bio"]);
// you can mutate
copy.bio = { name: "Jill", age: 33 };
// and it does not have side effect on original object
console.log(copy.bio, object.bio);
// prints: {name: 'Jill', age: 33} {name: 'James', age: 23}
Comments
Hope it will work for you.
const array= ["a","b"]
const obj = {
a: 1,
b:2,
c:3
}
const copyObj= { }
array.forEach((e)=>{
copyObj[e] = obj[e]? obj[e]: null
})
4 Comments
Hayk
Hi. Thanks for response. But in this case it would be a shallow copy right?
Hayk
Thanks again for your time. I refer to cases when object contains objects or arays itself. For instance if you have const object = {bio: {name: "James", age: 23}, hobbies: ["Fishing", "Hunting", "Coding"]} Even after copying, if i change copyObj.bio.name, it will be changed in the original array as well.
@Hayk In that case you can use external library like loadash. I think you are looking for something like loadash._omit method. Check this out google.com/amp/s/www.geeksforgeeks.org/lodash-_-omit-method/amp
You can iterate over your object keys with Object.keys()
const keys = Object.keys(yourObject);
keys.forEach((key, index) => {
console.log(`${key}: ${yourObject[key]}`);
});
From that iteration you can verify if the key you're exists on the array with keysYouWanToLook.includes(key);
the final code would be something like this:
const keysYouWanToLook = ['a','b'];
const keys = Object.keys(yourObject);
let result = {}
keys.forEach((key, index) => {
if(keysYouWanToLook.includes(key)){
result = { ...result, [key]:yourObject[key]}
}
});
console.log(result);
const cpy = JSON.parse(JSON.stringify(obj))orconst cpy = cloneDeep(obj). cloneDeep is a method from lodash