Sandeep Sharma Sandeep Sharma - 1 year ago 73
Javascript Question

Lodash : return first key of object whose 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 "".

After seeing comments: Now I'm also curious to know about

Does I need to go with native javascript(hard to read program in the cases if we use more than 2 if blocks) or lodash way(easily readable program solution in one line)?

Answer Source

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.indexOf("c") !== -1; });

or, using ES6 syntax,

_.findKey(obj, (item) => (item.indexOf("c") !== -1));

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 `` iteratee shorthand.
_.findKey(users, 'active');
// → 'barney'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download