Sia Sia - 3 months ago 13
JSON Question

Javascript - check if string is in json and identify the parent

I would like to create something to check if a value is in my json data and then retrieve group in which he belongs.

data = [{
"1" : ["1007","1020"],
"2" : ["1200","1493"],
"3" : ["6754","8652"],
}]

var value = '1200' #how to identify if 1200 is in group 2.


I have no clue on how I can do that. Any help would be useful!

Answer
data = [{
  "1" : ["1007","1020"],
  "2" : ["1200","1493"],
  "3" : ["6754","8652"],
}]

for (var i = 0; i < data.length; i++) {
    for (var key in data[i])
    {
        if (data[i][key].indexOf('1200') !== -1){
            console.log(key);
        }
    }
}

basically, you are looping through the array of objects and then looping through the keys of each object to test if your element belongs to the value of each key.