我有几个字符串数组,并给出了一个特定的输入键字符串,我试图返回相应的键。
例如,如果输入值是“a1”,它应该返回“aa”,因为“a1”是键“aa”的数组值的一部分。
inputKey = 'a1';
dict = {
'aa': ['a1', 'a2'],
'bb' : ['b1', 'b4', 'b6']
...
};
/
// _.contains())
我正在考虑遍历字典中的每个元素,如果数组中存在该值,则返回键。
这是最好的方法吗?(为一组值找到相应的键)换句话说(将某些特定值映射到另一个值)。
我知道您想要一种使用underscore
.
这是使用 functionfind
和 function的替代方法some
。
let inputKey = 'a1',
dict = { 'aa': ['a1', 'a2'], 'bb': ['b1', 'b4', 'b6'] },
result = Object.keys(dict).find(k => dict[k].some(d => d === inputKey));
console.log(result);
使用该功能包括
let inputKey = 'a1',
dict = { 'aa': ['a1', 'a2'], 'bb': ['b1', 'b4', 'b6'] },
result = Object.keys(dict).find(k => dict[k].includes(inputKey));
console.log(result);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句