Search code examples
javascriptnode.jses6-map

Check if a string is contained within a specific Map() key


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.


Solution

  • 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.