Dagrooms Dagrooms - 7 months ago 16
Javascript Question

Check if string is in array inside dictionary

I have a dictionary of strings to arrays of strings:

{"a":["b", "c"]}
. When indexing into the dictionary, I get an array of strings back, but checking if any string is in this array always returns false.
Here is the code setup:

var dict = {
"first":["a", "b", "c"]
}
if("a" in dict["first"]){
// Never hits this line
console.log("Found a!");
}


I'm pretty new to Javascript so I may be missing something about the setup of a dictionary object, but it seems pretty straightforward and I have professional experience in a few C languages so it is fairly disconcerting that this doesn't work. What is wrong here?

Answer

The in operator returns true if the specified property is in the specified object, Taken from here.

a is not a property it's an array value, array index is act as property and 0 in dict["first"] will be true here. So here you can use indexOf()

var dict = {
  "first": ["a", "b", "c"]
}
if (dict["first"].indexOf("a") > -1) {
  console.log("Found a!");
}

Comments