How to filter keys of an object with lodash?

前端 未结 5 1140
野趣味
野趣味 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)

提交回复
热议问题