Is it possible to check if a JS Map contains a value and have it return its key

ε祈祈猫儿з 提交于 2021-02-11 14:24:17

问题


I'm trying to find a way to look into a Map array value to see if it exists if it does return the Map key as a variable. this has stumped me for a bit now as I don't do much javascript.

const map = new Map([
        ["KEY1", ["dummy1","dummy2","dummy3"]],
        ["KEY2", ["dummy4","dummy5","dummy6","dummy7"]],
        ["KEY3", ["dummy8","dummy9"]],
    ]);

so say I have dummy4 as a var I want to look in map and see it there in the array of values with key2 and return the key into a new variable of sting "KEY2"


回答1:


I'm doing it this way to search for a certain value that could have many terms it might not be the best way its what I cam up with basically many values could be entered into an input but all relate to only one output

Based on a comment, I'm going to recommend a different way to build your lookup structure -

const terms =
  [ ["KEY1", ["dummy1","dummy2","dummy3"]]
  , ["KEY2", ["dummy4","dummy5","dummy6","dummy7"]]
  , ["KEY3", ["dummy8","dummy9"]]
  ]
  
const dict =
  new Map(terms.flatMap(([ k, vs ]) => vs.map(v => [ v, k ])))
  
console.log(dict.get("dummy2"))
console.log(dict.get("dummy5"))
console.log(dict.get("dummy7"))
console.log(dict.get("dummy9"))
console.log(dict.get("dummy0"))

Output -

KEY1
KEY2
KEY2
KEY3
undefined

This is more efficient because the Map structure provides instant lookup for any value and does not require a full .entries scan -

Map
  { "dummy1" -> "KEY1"
  , "dummy2" -> "KEY1"
  , "dummy3" -> "KEY1"
  , "dummy4" -> "KEY2"
  , "dummy5" -> "KEY2"
  , "dummy6" -> "KEY2"
  , "dummy7" -> "KEY2"
  , "dummy8" -> "KEY3"
  , "dummy9" -> "KEY3"
  }



回答2:


Loop through the entries:

function findValue(map, value) {
    for (const [k, arr] of map.entries()) {
        if (arr.includes(value)) {
            return k;
        }
    }
}


来源:https://stackoverflow.com/questions/65350948/is-it-possible-to-check-if-a-js-map-contains-a-value-and-have-it-return-its-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!