How to get object keys for true values in JavaScript


In this post, I would like to share a few easy ways of extracting keys from an object for truthy values in JavaScript. This kind of problem is quite common. The following examples will help you select the best solution for your case and save you time.

A truthy value in JavaScript

In JavaScript, a truthy value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy. A falsy values are as follows: false, 0, ”” (empty string), null, undefined, and NaN.

Let’s say; we have an object with some identifiers as keys and their status as values. In our case we will use an object with user identifiers as keys and active/inactive (true/false respectively) status as value.

const users = {
  LG4u9Uth8JfaVuSBc2y: true, // active
  LG4u9OJv5yD6dUqth9V: false, // inactive
  LG4u9vP9xjwHJm8PezV: true // active
  // ... more ...
}

Existing JavaScript functions

The first approach would be to use existing JavaScript functions such as Object.keys to and Array.filter.

The Object.keys() method returns an array of a given object’s own property names. The Array.filter method creates a new array with all elements that pass the test implemented by the provided function.

const identifiers = Object.keys(users)
const active = identifiers.filter(function(id) {
  return users[id]
})

Alternative approach with Lodash library

An alternative approach would be to use Lodash, universal JavaScript library. We will use pickBy and keys methods.

The pickBy(object, predicate) methods creates an object composed of the input object properties for which values, predicate function return truthy value. If you do not provide the predicate function, the method will automatically check checked whether a value is truthy or not. The keys(object) method creates an array of the own enumerable property names of the input object.

So in your example it would be:

const active = _.keys(_.pickBy(users))

Alternative approach with Underscore.js library

Another approach would be to use Underscore.js, JavaScript library. Underscore.js provides very similar methods to Lodash library. However, there are slight differences.

We will use the pick(object, predicate) and keys(object) methods. These methods work very similarly to pickBy and keys ones from Lodash library. The only difference is that the pick one would need to get a predicate function. To have the same behaviour as with Lodash library, we will use identity method.

So the code would be as follows:

var active = _.keys(_.pick(users, _.identity))

Tags:

#array #filter #javascript #lodash #underscore.js


You may also be interested in:



comments powered by Disqus