Return an object key only if value is true

后端 未结 3 1794
抹茶落季
抹茶落季 2020-12-03 13:52

How do i return an object key name only if the value of it is true?

I\'m using underscore and the only thing i see is how to return keys which is easy, i want to avo

3条回答
  •  没有蜡笔的小新
    2020-12-03 14:03

    There is another alternative, which could be used with Lodash library using two methods:

    • _.pickBy - it creates an object composed of the object properties. If there is no additional parameter (predicate) then all returned properties will have truthy values.
    • _.keys(object) - creates an array of keys from the given object

    So in your example it would be:

    var obj = {1001: true, 1002: false};
    var keys = _.keys(_.pickBy(obj));
    
    // keys variable is ["1001"]
    

    Using Underscore.js library, it would be very similar. You need to use _.pick and _.keys functions. The only difference is that _.pick would need to have predicate function, which is _.identity.

    So the code would be as follows:

    var obj = {1001: true, 1002: false};
    var keys = _.keys(_.pick(obj, _.identity));
    
    // keys variable is ["1001"]
    

    I hope that will help

提交回复
热议问题