【问题标题】:How to obtain different keys which have same values in a dictionary?如何获取字典中具有相同值的不同键?
【发布时间】:2019-05-11 13:32:02
【问题描述】:

我有一本像这样的字典,如您所见,我有两个相同的数组值用于两个不同的键。我的问题是:如何通过输入一个值来获得这两个键?我想获得所有具有相同值的键作为输出。这是因为在我的项目中,我只能在检测音符时使用尖锐或平坦(不能同时使用两者)。

var dictionary = {
  "Cmaj7": ["C","E","G","B"] ,     //majors
  "C#maj7": ["C#","F","G#","C"],
  "Dbmaj7":["C#","F","G#","C"]}

【问题讨论】:

  • 值数组是否总是以相同的方式排序?
  • 嗨!不,它们也可以是随机顺序。重要的是它们包含相同的字符串值
  • 数组过滤器,每个,包括?

标签: javascript arrays dictionary object key


【解决方案1】:

这样的?

var dictionary = {
  "Cmaj7": ["C","E","G","B"] ,     //majors
  "C#maj7": ["C#","F","G#","C"],
  "Dbmaj7":["C#","F","G#","C"]}
  
var newObj = {}
for (var o in dictionary) {
  var reverseKey = dictionary[o].join("_");
  if (!newObj[reverseKey]) newObj[reverseKey]=[];
  newObj[reverseKey].push(o);
}
console.log(newObj)

【讨论】:

    【解决方案2】:

    您可以像这样通过Array.filterArray.everyArray.someArray.includes 解决这个问题:

    var data = { "Cmaj7": ["C", "E", "G", "B"], "C#maj7": ["C#", "F", "G#", "C"], "Dbmaj7": ["C#", "F", "G#", "C"] }
    
    const e = Object.entries(data)
    const dubs = e.filter(([k1, v1]) => v1.every(v => e.some(([k2, v2]) => k1 != k2 && v2.includes(v))))
    const result = dubs.reduce((acc,[k,v]) => (acc[k] = v, acc), {})
    
    console.log(result)

    这个想法是获取每个键的值并过滤,以便每个值都包含在其余对象值中。

    您也可以通过Array.reduceArray.filter 获取具有相同值的键数组:

    var data = { "Cmaj7": ["C", "E", "G", "B"], "C#maj7": ["C#", "F", "G#", "C"], "Dbmaj7": ["C#", "F", "G#", "C"] }
    
    const result = Object.entries(data).reduce((r, [k,v], i, a) => {
      let key = v.join('-')
      r[key] = [...r[key] || [], k]
      return i == a.length-1 ? Object.values(r).filter(a => a.length > 1) : r
    }, {})
    
    console.log(...result)

    【讨论】:

      猜你喜欢
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 2014-04-27
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多