获取值为 true 的 JavaScript 对象的所有键 [英] Get all keys of a JavaScript object whose value is true

查看:31
本文介绍了获取值为 true 的 JavaScript 对象的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象 pks 并想提取值为 true 的所有键.

I have the object pks and would like to extract all keys where the value is true.

pks = {3: false, 7: true, 2: true}

有没有可以返回[7, 2]的下划线函数?我已经尝试过 _.invert 但我在这个过程中丢失了一个值,所以我正在寻找替代方法.

Is there an underscore function that can return [7, 2]? I’ve tried _.invert but I lost one of the values in the process so I’m looking for an alternative.

推荐答案

你可以使用内置函数来做到这一点,不需要下划线:

You can do this with builtin functions, no need for Underscore:

Object.keys(pks)
  .filter(function(k){return pks[k]})
  .map(Number)

这篇关于获取值为 true 的 JavaScript 对象的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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