Lodash:查找在其自己的数组中具有特定值的所有键

时间:2018-04-06 13:57:38

标签: javascript lodash

我正在使用lodash对以下数组执行以下任务:

let map = {
   "John": ["math", "physics", "chem"],
   "Lisa": ["bio", "chem", "history"],
   "Emily": ["math", "history", "javascript"];
}

使用lodash,如何返回有价值的密钥" javascript"在它的数组中,在这种情况下是Emily

我正在使用

_.keys(_.pickBy(map, e => {
    return (e == 'javascript');
}))

但这似乎不起作用

2 个答案:

答案 0 :(得分:4)

您可以使用findKeyincludes方法查找密钥。



let map = {
  "John": ["math", "physics", "chem"],
  "Lisa": ["bio", "chem", "history"],
  "Emily": ["math", "history", "javascript"]
}

const result = _.findKey(map, e => _.includes(e, 'javascript'))
console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
&#13;
&#13;
&#13;

要匹配值包含元素的多个键,您可以使用pickBy方法过滤属性,然后获取键。

&#13;
&#13;
let map = {
  "John": ["math", "physics", "chem"],
  "Lisa": ["bio", "chem", "history", "javascript"],
  "Emily": ["math", "history", "javascript"]
}

const result = _.keys(_.pickBy(map, e => _.includes(e, "javascript")))
console.log(result)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

要使用数组格式获取所有键,请使用以下代码

let map1 = {
"John": ["math", "physics", "chem"],
"Lisa": ["bio", "chem", "history","javascript"],
"Emily": ["math", "history", "javascript"];
}

 _.compact(_.map(map1,(v,k)=>{if(v.indexOf("javascript")>-1) return k; }))

这对我来说很好。