Pick object keys

JavaScript, Object · Oct 18, 2020

Picks the key-value pairs corresponding to the given keys from an object.

  • Use Array.prototype.reduce() to convert the filtered/picked keys back to an object with the corresponding key-value pairs if the key exists in the object.
const pick = (obj, arr) =>
  arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});

pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }

More like this

  • JavaScript Object Key Selection

    Pick and omit keys from JavaScript objects easily, using the snippets in this collection.

    Collection · 4 snippets

  • Omit object keys

    Omits the key-value pairs corresponding to the given keys from an object.

    JavaScript, Object · Oct 21, 2020

  • Pick matching object keys

    Creates an object composed of the properties the given function returns truthy for.

    JavaScript, Object · Oct 22, 2020

  • Omit matching object keys

    Creates an object composed of the properties the given function returns falsy for.

    JavaScript, Object · Oct 21, 2020