Return an object key only if value is true

后端 未结 3 1793
抹茶落季
抹茶落季 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:15

    If you're trying to combine filtering and iterating over an object you're usually after _.reduce (the Swiss Army Knife iterator):

    var trues = _(obj).reduce(function(trues, v, k) {
        if(v === true)
            trues.push(k);
        return trues;
    }, [ ]);
    

    Demo: http://jsfiddle.net/ambiguous/2et6T/

提交回复
热议问题