lost9123193 lost9123193 - 1 year ago 96
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.


[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 Source

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;}));


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

<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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download