pick / omitLoading saved progress…

pick / omit

pick and omit build a subset of an object. pick keeps only the keys you name; omit drops them and keeps the rest — they're complements. Their By variants, pickBy and omitBy, select by a predicate over each value instead of by a fixed key list. Together they're how you trim an object down to the fields you actually want.

Implement all four. pick(obj, keys) and omit(obj, keys) take an array of keys; pickBy(obj, predicate) and omitBy(obj, predicate) take a function called with (value, key). Each returns a new object without mutating the input.

Signature

function pick(obj, keys) {}    // keep the listed keys
function omit(obj, keys) {}    // drop the listed keys
function pickBy(obj, predicate) {} // keep where predicate(value, key) is truthy
function omitBy(obj, predicate) {} // keep where predicate(value, key) is falsy

Examples

pick({ a: 1, b: 2, c: 3 }, ['a', 'c']); // { a: 1, c: 3 }
omit({ a: 1, b: 2, c: 3 }, ['a', 'c']); // { b: 2 }
pickBy({ a: 1, b: 2, c: 3 }, (v) => v > 1); // { b: 2, c: 3 }
omitBy({ a: 0, b: 1, c: '' }, Boolean);     // { a: 0, c: '' }

Notes

  • pick and omit are complementspick keeps what you name, omit keeps everything else.
  • Own enumerable only — operate on the object's own enumerable keys; don't pull in inherited properties.
  • Missing keys are harmless — picking or omitting a key that isn't there simply has no effect.
  • pickBy/omitBy predicate — receives (value, key); pickBy keeps truthy results, omitBy keeps falsy ones (they're inverses).
  • New object, no mutation — always return a fresh object; leave the input untouched.
Loading editor…