Sandeep Sharma Sandeep Sharma - 7 months ago 488
Javascript Question

Lodash : return first key of object which value(i.e Array) has a given element (i.e string) in it

I have an object like:

var obj = {
"01": ["a","b"],
"03": ["c","d"],
"04": ["e","c"]
};


and I know an array element ( say "c") of the object key's value then How to find first key value i.e "03" using lodash without using if else?

I tried like this using lodash and if else:

var rId = "";
_.forOwn(obj, function (array, id) {
if (_.indexOf(array, "c") >= 0) {
rId = id;
return false;
}
});

console.log(rId); // "03"


Expected Result: first key i.e "03" if element matches else "".

Answer

Since you just want a way to be able to find a key using a simple Lodash command, the following should work:

_.findKey(obj, function(item) { return item[0] === "c"; });

or, using ES6 syntax,

_.findKey(obj, (item) => (item[0] === "c"));

This returns "03" for your example.

The predicate function - the second argument to findKey() - has automatic access to the value of the key. If nothing is found matching the predicate function, undefined is returned.

Documentation for findKey() is here.


Examples taken from the documentation:

var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};

_.findKey(users, function(o) { return o.age < 40; });
// → 'barney' (iteration order is not guaranteed)

// The `_.matches` iteratee shorthand.
_.findKey(users, { 'age': 1, 'active': true });
// → 'pebbles'

// The `_.matchesProperty` iteratee shorthand.
_.findKey(users, ['active', false]);
// → 'fred'

// The `_.property` iteratee shorthand.
_.findKey(users, 'active');
// → 'barney'