Pick matching object keys

JavaScript, Object · Oct 22, 2020

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

const pickBy = (obj, fn) =>
  Object.keys(obj)
    .filter(k => fn(obj[k], k))
    .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number');
// { 'a': 1, 'c': 3 }

More like this

  • Find matching keys

    Finds all the keys in the provided object that match the given value.

    JavaScript, Object · Nov 15, 2020

  • Omit object properties based on function

    Omits the key-value pairs corresponding to the keys of the object for which the given function returns falsy.

    JavaScript, Object · Oct 21, 2020

  • Find first matching key

    Finds the first key that satisfies the provided testing function. Otherwise undefined is returned.

    JavaScript, Object · Oct 22, 2020