Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert boolean object to array

How can I take a simple object with boolean values and convert it to an array where only those keys whose values are true end up in the array?

E.g.:

myObject = {
  option1: true,
  option2: false,
  option3: true,
  option4: true
}

becomes

['option1','option3','option4']

I tried using _.pick(myObject, Boolean) as suggested here, but that simply produced an empty object. I'm using Typescript, so if there's any Typescript magic I can use to accomplish this, I'm up for that, too.

like image 638
Nate Gardner Avatar asked Aug 25 '17 23:08

Nate Gardner


1 Answers

This is easily achievable with vanilla js.

let myObject = {
  option1: true,
  option2: false,
  option3: true,
  option4: true
}

let array = Object.keys(myObject).filter(key => myObject[key]);

console.log(array);

You can see a working example here.

like image 182
toskv Avatar answered Oct 06 '22 00:10

toskv