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?
Advertisement
Answer
JavaScript
x
20
20
1
// By defining Keys as keys of T, you get autocompletion
2
// Also by setting mapped type as return you only get
3
// the props you have copied in the return
4
const getSubset = <T, Keys extends keyof T, SubSet extends { [K in Keys]: T[K] }>(
5
obj: T,
6
keys: Keys[]
7
): SubSet => {
8
return keys.reduce((acc, key) => ({ [key]: obj[key], acc }), <SubSet>{});
9
};
10
11
const object = { bio: { name: "James", age: 23 }, hobbies: ["Fishing", "Hunting", "Coding"] };
12
// now copy will only show you bio and not hobbies
13
const copy = getSubset(object, ["bio"]);
14
// you can mutate
15
copy.bio = { name: "Jill", age: 33 };
16
17
// and it does not have side effect on original object
18
console.log(copy.bio, object.bio);
19
// prints: {name: 'Jill', age: 33} {name: 'James', age: 23}
20