Lodash:返回其值(即Array)中包含给定元素(即字符串)的对象的第一个键

San*_*rma 21 javascript lodash

我有一个像这样的对象:

var obj = {
  "01": ["a","b"],
  "03": ["c","d"],
  "04": ["e","c"]
};
Run Code Online (Sandbox Code Playgroud)

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

我尝试使用lodash和if if:

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

console.log(rId); // "03"
Run Code Online (Sandbox Code Playgroud)

预期结果:第一个键,即"03",如果元素匹配"".

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

我是否需要使用本机javascript(如果我们使用超过2个if块的情况下难以阅读的程序)或lodash方式(在一行中易于阅读的程序解决方案)?

Aks*_*jan 37

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

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

或者,使用ES6语法,

_.findKey(obj, (item) => (item.indexOf("c") !== -1));
Run Code Online (Sandbox Code Playgroud)

这将为您的示例返回"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'
Run Code Online (Sandbox Code Playgroud)


Ром*_*еев 7

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

Object.keys(obj).filter(x => obj[x].includes("c"))[0]
Run Code Online (Sandbox Code Playgroud)

  • 好点子!您甚至可以使用`.find(...)`而不是`.filter(...)[0]`:`Object.keys(obj).find(x => obj [x] .includes("c "))` (2认同)