gpt4 book ai didi

javascript - Lodash:在自己的数组中找到所有具有特定值的键

转载 作者:行者123 更新时间:2023-11-29 16:37:39 26 4
gpt4 key购买 nike

我正在使用 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');
}))

但这似乎不起作用

最佳答案

您可以使用findKeyincludes 方法来查找 key 。

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>

要匹配值包含元素的多个键,您可以使用 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)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

关于javascript - Lodash:在自己的数组中找到所有具有特定值的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49694507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com