我正在使用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');
}))
但这似乎不起作用
答案 0 :(得分:4)
您可以使用findKey
和includes
方法查找密钥。
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;
要匹配值包含元素的多个键,您可以使用pickBy
方法过滤属性,然后获取键。
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;
答案 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; }))
这对我来说很好。