简体   繁体   中英

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 ie "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 ie "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)?

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 `_.property` iteratee shorthand.
_.findKey(users, 'active');
// → 'barney'

具有讽刺意味的是,没有任何库存就没有更难实现。

Object.keys(obj).filter(x => obj[x].includes("c"))[0]

Here comes a single liner answer from the future. Currently only works in Firefox 47 on. Part of ES7 proposal.

 var obj = { "01": ["a","b"], "03": ["c","d"], "04": ["e","c"] }, res = Object.entries(obj).find(e => e[1].includes("c"))[0]; document.write(res); 

As an alternative solution: consider native Javascript approach using Object.keys and Array.some functions:

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

Object.keys(obj).some(function(k) { return obj[k].indexOf(search_str) !== -1 && (key = k); });
// the same with ES6 syntax:
// Object.keys(obj).some((k) => obj[k].indexOf(search_str) !== -1 && (key = k));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM