如何获得字典中具有相同值的不同键? [英] How to obtain different keys which have same values in a dictionary?

查看:354
本文介绍了如何获得字典中具有相同值的不同键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dictionary like this one and as you can see, I have two identical array values for two different keys. My question is: how can I get these two keys by giving in input one values? I'd like to obtain as output all the keys that have the same values. This is because in my project I can only use sharp or flat (not both) in the detection of a note.

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

推荐答案

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

You can solve this via Array.filter,Array.every, Array.some and Array.includes like this:

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)

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

The idea is to get the values of each key and filter then so that every one of the values are included in the rest of the object values.

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

You can also just get an array of the keys with same values via Array.reduce and Array.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)

这篇关于如何获得字典中具有相同值的不同键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆