Back to Snippets
CODE
Object Property Filtering (Pick)
Description
Creates a new object with only specified properties, ideal for removing unnecessary fields from API requests
Code
/**
* Pick specified properties from object
* @param obj Target object
* @param keys Array of properties to keep
* @returns New object with only specified properties
*/
function pickObject<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
return keys.reduce((acc, key) => {
if (obj.hasOwnProperty(key)) {
acc[key] = obj[key];
}
return acc;
}, {} as Pick<T, K>);
}
// Usage Example
const user = { id: 1, name: "John", email: "[email protected]", password: "secret" };
const safeUser = pickObject(user, ["id", "name", "email"]);
console.log(safeUser); // { id: 1, name: "John", email: "[email protected]" }Usage
Perfect for sanitizing form data before API requests, removing sensitive fields, or creating minimal data objects