jumbopap
jumbopap

Reputation: 4147

List comprehension-like filtering of object in JavaScript

I have a simple array that looks like

obj = {1:false, 2:true, 3:true}

I would like to retrieve an array of all keys in the object that have a value of true.

In python you can just do

>>> [key for key in obj if obj[key]]
[2, 3]

Is there a one-line or other simple way of doing this in Javascript? I also have access to lodash.

Upvotes: 5

Views: 1337

Answers (3)

Matus Dubrava
Matus Dubrava

Reputation: 14502

Using new javascript syntax, you can do it like this.

const obj = {1:false, 2:true, 3:true};

const res = Object.keys(obj).filter(k => obj[k]);

console.log(res); 

Upvotes: 1

dansalmo
dansalmo

Reputation: 11704

You can do this in any Ecma5 capable browser using Object.keys and Array.filter:

> Object.keys(obj).filter(function(i) {return obj[i]});
> ["2", "3"]

Upvotes: 2

Bruno Calza
Bruno Calza

Reputation: 2780

You can do it in Firefox 30+.

obj = {1:false, 2:true, 3:true};
[for (key of Object.keys(obj)) if (obj[key]) key ]; 

results

["2", "3"]

Currently, it is the only browser that implements Array Comprehension

Upvotes: -1

Related Questions