Create a new object with only the specified keys. Immutable subset of an object.
export function pick<T extends object, K extends keyof T>(
obj: T,
keys: K[]
): Pick<T, K> {
return keys.reduce((acc, key) => {
if (key in obj) acc[key] = obj[key];
return acc;
}, {} as Pick<T, K>);
}
// pick({ a: 1, b: 2, c: 3 }, ['a', 'c']) => { a: 1, c: 3 }
Pass an object and an array of keys. Returns a new object with only those keys (if present).
Whitelist fields before sending to API or building a subset.
pick(user, ['id', 'name', 'email']);