Skip to content
GreenSnippets

Pick and omit object keys

Build a new object with only some keys, or without some keys, without mutating the original.

JavaScript
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

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.