How to filter keys of an object with lodash?

前端 未结 5 1128
野趣味
野趣味 2020-11-28 23:51

I have an object with some keys, and I want to only keep some of the keys with their value?

I tried with filter:

相关标签:
5条回答
  • 2020-11-29 00:23

    A non-lodash way to solve this in a fairly readable and efficient manner:

    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
    }
    
    const result = filterByKeys(myObject, ['a', 'd', 'e']) // {a: 1, d: null}
    console.log(result)

    0 讨论(0)
  • 2020-11-29 00:24

    Lodash has a _.pickBy function which does exactly what you're looking for.

    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>

    0 讨论(0)
  • 2020-11-29 00:29

    Here is an example using lodash 4.x:

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

    0 讨论(0)
  • 2020-11-29 00:42

    Just change filter to omitBy

    const data = { aaa: 111, abb: 222, bbb: 333 };
    const result = _.omitBy(data, (value, key) => !key.startsWith("a"));
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

    0 讨论(0)
  • 2020-11-29 00:45

    Native ES2019 one-liner

    const data = {
      aaa: 111,
      abb: 222,
      bbb: 333
    };
    
    const filteredByKey = Object.fromEntries(Object.entries(data).filter(([key, value]) => key.startsWith("a")))
    
    console.log(filteredByKey);

    0 讨论(0)
提交回复
热议问题