如何从对象值中获取键?

时间:2018-12-01 16:26:35

标签: javascript dictionary object key

我正在尝试建立一个和弦字典,该字典以和弦的名称为键,并以组成该和弦的MIDI数字(音符)作为值的数组。但是,我遇到了问题,一旦将geti()的数字作为数组的输入作为函数的输入键,就无法获取字典的键。我该怎么办?在此先感谢:)

 var dictionary = {
  "Cmaj7": [60,64,67,71]
};

const getKey = (obj,val) => Object.keys(obj).find(key => obj[key] === val);

console.log(getKey(dictionary,[60,64,67,71]));

3 个答案:

答案 0 :(得分:0)

您不能使用===运算符比较两个数组。使用以下功能:

function compareArrays(a, b) {
  if(a.length != b.length) return false;
  for(let i = 0; i < a.length; i++) {
    if(a[i] !== b[i]) return false;
  }
  return true;
}

只需将obj[key] === val替换为compareArrays(obj[key], val),它就可以工作,假设所有值都将是简单数组。如果没有,则要在函数中检查。

答案 1 :(得分:0)

假设您要搜索数组,则可以使用函数plt.imshow(image, extent=[0, 1280, 0, 720]) 来检查数组every中的每个值是included

这是假设我们正在处理数组

val

答案 2 :(得分:0)

var dictionary = {
  "Cmaj7": [60,64,67,71]
};

function getKey(obj, arr) {

  // Find the first object that satisfies the condition...
  const found = Object.entries(obj).find(([key, notes]) => {

    // ...that all the notes in the object are included in the
    // array that was passed in. As long as the notes array and the
    // query array are the same length, the notes can be in any order
    return arr.length === notes.length && arr.every(note => notes.includes(note));
  });

  // If `found` is an Object.entries array return the key
  // otherwise return the error
  return found && found[0] || 'Key not found';
}

// Same order
const key = getKey(dictionary, [60, 64, 67, 71]);
console.log(key);

// Different order
const key2 = getKey(dictionary, [71, 64, 67, 60]);
console.log(key2);

// Missing note
const key3 = getKey(dictionary, [71, 64, 60]);
console.log(key3);