如何获得字典中具有相同值的不同键?

时间:2018-12-10 15:56:38

标签: javascript arrays dictionary object key

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

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

2 个答案:

答案 0 :(得分:0)

像这样吗?

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)

答案 1 :(得分:0)

您可以通过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)