Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 723
jumbopap Avatar asked Oct 31 '22 14:10

jumbopap


2 Answers

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"]
like image 84
dansalmo Avatar answered Nov 10 '22 10:11

dansalmo


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); 
like image 25
Matus Dubrava Avatar answered Nov 10 '22 09:11

Matus Dubrava