javascript 仅当 value 为 true 时才返回对象键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25095789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return an object key only if value is true
提问by user3299182
How do i return an object key name only if the value of it is true?
仅当它的值为 true 时,我如何返回对象键名称?
I'm using underscore and the only thing i see is how to return keys which is easy, i want to avoid redundant iterations as much as possible:
我正在使用下划线,我唯一看到的是如何轻松返回键,我想尽可能避免冗余迭代:
example:
例子:
Object {1001: true, 1002: false}
I want an array with only 1001 in it...
我想要一个只有 1001 的数组...
回答by adeneo
Object.keysgets the keys from the object, then you can filterthe keys based on the values
Object.keys从对象中获取键,然后您可以根据值过滤键
var obj = {1001: true, 1002: false};
var keys = Object.keys(obj);
var filtered = keys.filter(function(key) {
return obj[key]
});
回答by Tom
There is another alternative, which could be used with Lodashlibrary using two methods:
还有另一种选择,可以使用两种方法与Lodash库一起使用:
_.pickBy
- it creates an object composed of the object properties. If there is no additional parameter (predicate) then all returned properties will have truthyvalues._.keys(object)
- creates an array of keys from the given object
_.pickBy
- 它创建一个由对象属性组成的对象。如果没有附加参数(谓词),则所有返回的属性都将具有真值。_.keys(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.jslibrary, 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
.
使用Underscore.js库,它会非常相似。您需要使用_.pick
和_.keys
功能。唯一的区别是_.pick
需要有谓词函数,即_.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
我希望这会有所帮助
回答by mu is too short
If you're trying to combine filtering and iterating over an object you're usually after _.reduce
(the Swiss Army Knife iterator):
如果您尝试结合过滤和迭代您通常需要的对象_.reduce
(瑞士军刀迭代器):
var trues = _(obj).reduce(function(trues, v, k) {
if(v === true)
trues.push(k);
return trues;
}, [ ]);