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.

2
  • 7
    Object.entries(myObject).filter(([_,v]) => v).map(([k]) => k) Commented Aug 25, 2017 at 23:35
  • Gorgeous. This comment should be an (and the) answer! Commented Aug 26, 2017 at 0:21

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good solution with pure javascript :) .. but why you mentioned vanilla js?
ooh.. just a alias.. anyway, +1 ^^
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>

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.