仅当 value 为 true 时才返回对象键 [英] Return an object key only if value is true

查看:33
本文介绍了仅当 value 为 true 时才返回对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅在对象键名称为真时才返回对象键名称?

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 avoid redundant iterations as much as possible:

示例:

Object {1001: true, 1002: false} 

我想要一个只有 1001 的数组...

I want an array with only 1001 in it...

推荐答案

Object.keys 从对象中获取密钥,然后你可以过滤基于值的键

Object.keys gets the keys from the object, then you can filter the keys based on the values

var obj = {1001: true, 1002: false};

var keys = Object.keys(obj);

var filtered = keys.filter(function(key) {
    return obj[key]
});

小提琴

这篇关于仅当 value 为 true 时才返回对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆