Filtering object by keys in lodash

时间:2016-02-12 19:24:15

标签: javascript lodash

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)
  }
}

3 个答案:

答案 0 :(得分:10)

您可以使用lodash中的pickBy来执行此操作。 (https://lodash.com/docs#pickBy

此示例返回一个对象,其对象以“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}

答案 1 :(得分:6)

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;
    });
  }
}

答案 2 :(得分:4)

这是使用lodash执行此操作的简洁方法 - reduce()set()是您的朋友。

_.reduce(data, (result, value, key) => key.match(pattern) ? 
  _.set(result, key, value) : result, {});