【问题标题】:How to get a key from Object values?如何从对象值中获取键?
【发布时间】:2018-12-01 16:26:35
【问题描述】:

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

 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]));

【问题讨论】:

  • 您正在比较内存中的不同对象。
  • dictionary.Cmaj7 !== val
  • 那我应该怎么改功能呢?

标签: javascript dictionary object key


【解决方案1】:

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);

【讨论】:

  • 嗨!我还有另一个问题,但它是在我的项目上工作时出现的。现在我有两个相同的向量,可以引用两个不同的键。但我不知道如何让你函数返回两个不同的键相同的值(数组) 可以做什么?提前谢谢你:)
  • 你说得对,对不起,这是我的新问题的链接:stackoverflow.com/questions/53709238/…
【解决方案2】:

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

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),它应该可以工作,假设所有值都将是简单的数组。如果没有,您想在函数中检查它。

【讨论】:

    【解决方案3】:

    假设您正在搜索数组,您可以使用函数every 来检查数组val 中的每个值是否为included

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

    var dictionary = {"Cmaj7": [60,64,67,71]},
        getKey = (obj,val) => Object.keys(obj).find(key => obj[key].length === val.length && obj[key].every((kn) => val.includes(kn)));
    
    console.log(getKey(dictionary,[60,64,71,67]));

    【讨论】:

    • 非常感谢您的回答!但我注意到它不起作用如果我想在 getKey() 函数中放入具有相同元素但以随机顺序排列的数组(因为当我弹奏 MIDI 键盘时,可能会随机接收 MIDI 消息),可以是什么变了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多