首页 文章

如何使用lodash过滤对象的键?

提问于
浏览
142

我有一个带有一些键的对象,我想只保留一些键值?

我试过 filter

var data = {
  "aaa":111,
  "abb":222,
  "bbb":333
};

var result = _.filter(data, function(value, key) {
  return key.startsWith("a");
})

console.log(result);

但它打印一个数组:

[111, 222]

这不是我想要的 .

如何用lodash做到这一点?或者其他什么,如果lodash不工作?

现场演示:http://jsbin.com/moqufevigo/1/edit?js,output

4 回答

  • 14

    以非常可读和有效的方式解决此问题的非lodash方法:

    function filterByKeys(obj, keys = []) {
      const filtered = {}
      keys.forEach(key => {
        if (obj.hasOwnProperty(key)) {
          filtered[key] = obj[key]
        }
      })
      return filtered
    }
    
    const myObject = {
      a: 1,
      b: 'bananas',
      d: null
    }
    
    filterByKeys(myObject, ['a', 'd', 'e']) // {a: 1, d: null}
    
  • 32

    Lodash has a _.pickBy function 这正是您正在寻找的 .

    var thing = {
      "a": 123,
      "b": 456,
      "abc": 6789
    };
    
    var result = _.pickBy(thing, function(value, key) {
      return _.startsWith(key, "a");
    });
    
    console.log(result.abc) // 6789
    console.log(result.b)   // undefined
    
    <script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
    
  • 2

    只需将过滤器更改为omitBy

    var result = _.omitBy(data, function(value, key) {
         return !key.startsWith("a");
     })
    
  • 219

    以下是使用 lodash 4.x的示例:

    var data = {
      "aaa":111,
      "abb":222,
      "bbb":333
    };
    
    var result = _.pickBy(data, function(value, key) {
      return key.startsWith("a");
    });
    
    console.log(result);
    // Object {aaa: 111, abb: 222}
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>
    <strong>Open your javascript console to see the output.</strong>
    

相关问题