Filtering object properties based on value

前端 未结 7 757
孤独总比滥情好
孤独总比滥情好 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:31

    If you're using lodash, I'd recommend something like this:

    var object = {
        propA: true,
        propB: true,
        propC: false,
        propD: true,
    };
    
    _.pick(object, _.identity);
    // →
    // {
    //   propA: true,
    //   propB: true,
    //   propD: true
    // }
    

    The pick() function generates a new object that includes properties that the callback returns truthy for. So we can just use the identity() function as the callback, since it'll just return each property value.

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