13

I wrote the function below to return all keys in an object that match a specific pattern. It seems really round-about because there's no filter function in lodash for objects, when you use it all keys are lost. Is this the only way to filter an objects keys using lodash?

export function keysThatMatch (pattern) {
  return (data) => {
    let x = _.chain(data)
    .mapValues((value, key) => {
      return [{
        key: key,
        value: value
      }]
    })
    .values()
    .filter(data => {
      return data[0].key.match(pattern)
    })
    .zipWith(data => {
      let tmp = {}
      tmp[data[0].key] = data[0].value
      return tmp
    })
    .value()
    return _.extend.apply(null, x)
  }
}
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • 1
    Possible duplicate of [How to filter keys of an object with lodash?](https://stackoverflow.com/questions/30726830/how-to-filter-keys-of-an-object-with-lodash) – trushkevich Aug 22 '17 at 12:31

3 Answers3

27

You can use pickBy from lodash to do this. (https://lodash.com/docs#pickBy)

This example returns an object with keys that start with 'a'

var object = { 'a': 1, 'b': '2', 'c': 3, 'aa': 5};

o2 = _.pickBy(object, function(v, k) {
    return k[0] === 'a';
});

o2 === {"a":1,"aa":5}
bwbrowning
  • 6,200
  • 7
  • 31
  • 36
  • Thank you! I was looking for an answer that would "filter" an object but would return an object instead. This worked out perfectly – Eric Sep 06 '19 at 08:00
  • This should be marked as the correct answer, the question raised was how to do it with lodash, not if it can be done without it. – Eli Himself Feb 10 '21 at 10:39
7

I don't think you need lodash for this, I would just use Object.keys, filter for matches then reduce back down to an object like this (untested, but should work):

export function keysThatMatch (pattern) {
  return (data) => {
    return Object.keys(data).filter((key) => {
      return key.match(pattern);
    }).reduce((obj, curKey) => {
      obj[curKey] = data[curKey];
      return obj;
    });
  }
}
Rob M.
  • 35,491
  • 6
  • 51
  • 50
5

Here's a succinct way to do this with lodash - reduce() and set() are your friends.

_.reduce(data, (result, value, key) => key.match(pattern) ? 
  _.set(result, key, value) : result, {});
Adam Boduch
  • 11,023
  • 3
  • 30
  • 38