Lodash:返回对象的第一个键,该对象的值(即数组)中有一个给定的元素(即字符串)



我有一个类似于的对象

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

并且我知道对象键值的数组元素(比如"c"),那么如何使用lodash找到第一个键值,即"03"而不使用if else

我试过这样使用lodash,如果其他:

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

预期结果:如果元素匹配else",则第一个关键字即"03"

看到评论后:现在我也很想知道

我需要使用本地javascript(如果我们使用超过2if块,则在这种情况下很难读取程序)还是lodash方式(一行中的可读程序解决方案)?

由于您只想找到一种使用简单Lodash命令查找密钥的方法,因此以下方法应该有效:

_.findKey(obj, function(item) { return item.indexOf("c") !== -1; });

或者,使用ES6语法,

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

对于您的示例,这将返回"03"。

谓词函数是findKey()的第二个参数,它可以自动访问键的值。如果没有发现与谓词函数匹配的内容,则返回undefined

此处提供了findKey()的文档。


文件示例:

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]

这里有一个来自未来的线性答案。目前只适用于Firefox 47上。ES7提案的一部分。

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

作为替代解决方案:考虑使用Object.keysArray.some函数的本地Javascript方法:

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"

相关内容

最新更新