Skip to the code
cf.

pick and omit

Write two functions. pick(obj, keys) returns a new object with only the listed keys of obj. omit(obj, keys) returns a new object with every key of obj except the listed ones.

pick copies a listed key only when obj has it as its own property. Missing keys and inherited ones, like toString, are left out; a key whose value is undefined is kept. omit copies the own enumerable string keys of obj, the ones Object.keys lists, minus the listed ones.

Both always return a new object, and neither changes obj.

const user = { id: 1, name: "Ada", password: "hunter2" };
 
pick(user, ["id", "name"]); // { id: 1, name: "Ada" }
omit(user, ["password"]);   // { id: 1, name: "Ada" }
pick(user, ["email"]);      // {}

What the tests check

  1. pick keeps only the listed keys
    expect(pick({ a: 1, b: 2, c: 3 }, ["a", "c"])).toEqual({ a: 1, c: 3 });
    
  2. pick leaves out keys the object doesn't have
    expect(pick({ a: 1 }, ["a", "missing"])).toEqual({ a: 1 });
    
  3. pick ignores inherited properties
    expect(pick({ a: 1 }, ["a", "toString"])).toEqual({ a: 1 });
    const child = Object.create({ inherited: true });
    expect(pick(child, ["inherited"])).toEqual({});
    
  4. pick keeps a key whose value is undefined
    expect(Object.keys(pick({ a: undefined, b: 1 }, ["a"]))).toEqual(["a"]);
    
  5. omit drops the listed keys
    expect(omit({ a: 1, b: 2, c: 3 }, ["b"])).toEqual({ a: 1, c: 3 });
    expect(omit({ a: 1, b: 2 }, ["a", "b", "missing"])).toEqual({});
    
  6. omit leaves out inherited properties
    const child = Object.create({ inherited: true });
    child.own = 1;
    expect(omit(child, [])).toEqual({ own: 1 });
    
  7. both return a new object and leave the original alone
    const source = { a: 1, b: 2 };
    expect(pick(source, ["a", "b"])).not.toBe(source);
    expect(omit(source, [])).not.toBe(source);
    omit(source, ["a"]);
    expect(source).toEqual({ a: 1, b: 2 });
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).