Filtering object by keys in lodash

后端 未结 3 1128
-上瘾入骨i
-上瘾入骨i 2021-02-20 03:42

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,

相关标签:
3条回答
  • 2021-02-20 04:09

    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, {});
    
    0 讨论(0)
  • 2021-02-20 04:10

    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}
    
    0 讨论(0)
  • 2021-02-20 04:11

    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;
        });
      }
    }
    
    0 讨论(0)
提交回复
热议问题