Filtering object properties based on value

前端 未结 7 762
孤独总比滥情好
孤独总比滥情好 2020-12-14 16:40

Is there some elegant way of filtering out falsey properties from this object with lodash/underscore? Similar to how _.compact(array) removes falsey elements fr

7条回答
  •  粉色の甜心
    2020-12-14 17:26

    Prior to Lodash 4.0

    You want _.pick, it takes a function as an argument and returns an object only containing the keys for which that function returns truthy. So you can do:

    filtered = _.pick(obj, function(value, key) {return value;})
    

    Or even more succinctly:

    filtered = _.pick(obj, _.identity)
    

    Lodash 4.0

    Lodash 4.0 split the _.pick function into _.pick, which takes an array of properties, and _.pickBy which takes a function. So now it'd be

    filtered = _.pickBy(obj, function(value, key) {return value;})
    

    Or, since _.pickBy defaults to using _.identity as it's second argument, it can just be written as:

    filtered = _.pickBy(obj);
    

提交回复
热议问题