user3111903
user3111903

Reputation: 43

How to return an array of properties that match pattern using lodash

Is there any way using the lodash function to return an array of properties that match to a pattern?

_.magicMethod({a:'hi', b:13, c:undefined, d:null, e:null}, null)

return => `['d','e']`

I checked the docs but I don't found nothing :/ Thank you.

Upvotes: 3

Views: 1222

Answers (1)

Retsam
Retsam

Reputation: 33409

There's probably not a single function version of it; but you can do:

function magicMethod(obj, value) {
    return _.keys(_.pick(obj, function(propertyValue) {
         return propertyValue === value;
    }));
}

_.pick creates an object with only the properties with values matching the specified value, then _.keys extracts the keys of that object.

Upvotes: 5

Related Questions