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
// 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}