使用下划线循环遍历键值对象

Looping over key value object with underscore

我有几个 字符串数组 并给定了一个特定的 输入键 字符串我正在尝试 return 相应的关键。

例如,如果输入值是 'a1',它应该 return 'aa' 因为 'a1' 是键 'aa' 的数组值的一部分。

 inputKey = 'a1';
 dict = {
    'aa': ['a1', 'a2'],
    'bb' : ['b1', 'b4', 'b6']
    ...
  };

  /
  // _.contains())

我正在考虑遍历字典中的每个元素,如果数组中存在该值,则 return 键。

这是最好的方法吗? (为值数组找到相应的键)换句话说(将一些特定值映射到另一个值)。

.find() and .includes()应该足够简单了:

let inputVal = 'a1';
let inputVal2 = 'b1';
let inputVal3 = 'c1';

let dict = {
  'aa': ['a1', 'a2'],
  'bb' : ['b1', 'b4', 'b6']
};

let foundKey = Object.keys(dict).find(key => dict[key].includes(inputVal));
let foundKey2 = Object.keys(dict).find(key => dict[key].includes(inputVal2));
let foundKey3 = Object.keys(dict).find(key => dict[key].includes(inputVal3));

console.log(foundKey);
console.log(foundKey2);
console.log(foundKey3);

我知道你想要一种使用 underscore 的方法。

这是使用函数 find 和函数 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);