Dagrooms
Dagrooms

Reputation: 1564

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?

Upvotes: 2

Views: 1202

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115242

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!");
}

Upvotes: 3

Vikrant Kashyap
Vikrant Kashyap

Reputation: 6866

try this. this will work to you.

var dict = {
    "first":["c", "b", "a"]
};
console.log(dict.first);
for( var x in dict.first){

    if(dict.first[x]=="a")
    {
     console.log("index of a :"+ x);
     break;
    }
}
}

Upvotes: 0

Related Questions