Pick and omit object keys
Build a new object with only some keys, or without some keys, without mutating the original.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
function pick(object, keys) {
const out = {};
for (const key of keys) {
if (Object.hasOwn(object, key)) out[key] = object[key];
}
return out;
}
function omit(object, keys) {
const drop = new Set(keys);
return Object.fromEntries(Object.entries(object).filter(([key]) => !drop.has(key)));
}Example / expected output
pick({ id: 1, name: "Ada", password: "x" }, ["id", "name"]) // { id: 1, name: "Ada" }
omit({ id: 1, name: "Ada", password: "x" }, ["password"]) // { id: 1, name: "Ada" }How it works
Handy for whitelisting request fields or stripping secrets before logging. Both helpers return new objects and only look at own properties.
Related snippets
- TypeScript Tested
Typed Object.keys and Object.entries
Helpers that keep key types instead of widening to string, for objects you know the shape of.
- JavaScript Tested
Deep merge plain objects
Recursively merge configuration objects without mutating the inputs and without prototype pollution.
- JavaScript Tested
Deep equality check
Compare two values structurally, including nested objects, arrays, Dates, Maps and Sets.
- JavaScript Tested
Deep clone an object with structuredClone
Copy nested objects, arrays, Maps, Sets and Dates without sharing references, using the built-in structuredClone.

