lost9123193 lost9123193 - 4 months ago 28
Javascript Question

Filtering Object Array to only contain Key using Lodash

I have the following object array:

{
running: false,
swimming: false,
drawing: true
}


I want to filter the object array with only those that have false properties. From there I want to get only the keys of the array.

eg.

[running, swimming]


I have the first part of removing values that have truth booleans through the following:

var filtered = _.pick(hobbies, function(value, key) {return !value;});


What would be the best way to "flatten" the current array so that I only have the key values?

Answer

The Lodash _.keys() function provides precisely what you are asking for:

var hobbies = {
    running: false,
    swimming: false,
    drawing: true
};

var filtered = _.keys(_.pick(hobbies, function(value) {return !value;}));

console.log(filtered);

// alternate approach using chain notation
var keys = _
    .chain(hobbies)
    .pick(v => !v)
    .keys();

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

Note that in Lodash 4.x, _.pick() has changed and you should instead use _.pickBy() aboce.