0

I have a map which i am populating from a json file, similar to the below

key: ConfigItem
value: Var1,Var2,Var3


key: ConfigItem2
value: Var1,Var2,Var3,var4


key: ConfigItem3
value: true

i want to be able to run an if statement to check if a value is contained within the "ConfigItem" key, and if so, do something.

I looked at map.get and map.has but i can't seem to be able to figure out how to search a specific key and return if it contains a specific value.

Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
Red Spider
  • 25
  • 2
  • 6
  • There is no way to customize the equality algorithm that a map uses if that's what you want. There is a `keys` property that you can iterate however. If your configuration is stored as JSON you shouldn't be using a Map at all... – Aluan Haddad Sep 29 '18 at 19:02
  • @AluanHaddad Yes the config is stored as json, however i wanted a map so that i could update values at runtime without having to reload the app.js – Red Spider Sep 29 '18 at 19:08
  • A Map doesn't provide anything like that. If you need to refresh config from a file you can do so using the file system in a nodejs app or by making an http request in a browser app – Aluan Haddad Sep 29 '18 at 19:12
  • 1
    We might be able to help you better if you were to show us actual code rather than pseudo-code. If the value at your specific key is an array, use something like what's in [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/q/237104/215552). – Heretic Monkey Sep 29 '18 at 19:20
  • What exactly are you storing as the value, arrays? Comma-separated strings? – Bergi Sep 29 '18 at 20:06

1 Answers1

0

You seem to be looking for

const map = new Map([
    ["ConfigItem", ["Var1","Var2","Var3"]],
    ["ConfigItem2", ["Var1","Var2","Var3","var4"]],
    ["ConfigItem3", true],
]);

if (map.get("ConfigItem").includes("Var2")) {
    …
}

Notice this just uses Map get to access the array value for the ConfigItem key, but then uses the normal Array includes method to check if the specific string is contained in it.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • @MohammedEssehemy It seems that the OP already knows that his map has an entry for `ConfigItem`. – Bergi Sep 29 '18 at 20:14
  • I thought it would be more safe if he isn't sure that the key exists. but if the case as you describe then that's totally fine. – Mohammed Essehemy Sep 29 '18 at 20:19