5

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.

000
  • 26,951
  • 10
  • 71
  • 101
Nate Gardner
  • 1,577
  • 1
  • 16
  • 37

3 Answers3

12

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.

toskv
  • 30,680
  • 7
  • 72
  • 74
7

A lodash solution is to use lodash#pickBy and lodash#keys to get all truthy keys.

var result = _(myObject).pickBy().keys().value();

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

var result = _(myObject).pickBy().keys().value();

console.log(result);
.as-console-wrapper{min-height:100%;top:0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
ryeballar
  • 29,658
  • 10
  • 65
  • 74
0

in map function of Lodash it also handle Object, instead of a collection. using lodash the simplest solution will be using _.reduce.

Ohk.. let's see how _.map works with object:

var array = _(myObject).map((v, k)=> v && k).compact().value();

var myObject = {
  option1: true,
  option2: false,
  option3: true,
  option4: true
}
var array = _(myObject).map((v, k)=> v && k).compact().value();

console.log(array)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

With the same concept, (that lodash and underscore handle object if you pass in place of array) you can use _.reduce function and do the trick in one go:

var array = _.reduce(myObject, (i, v, k) => v && !i.push(k) || i, []);

var myObject = {
  option1: true,
  option2: false,
  option3: true,
  option4: true
}
var array = _.reduce(myObject, (i, v, k) => v && !i.push(k) || i, []);

console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32