0

Here is the JSON object:

{
  "stats":{
    "ie":{
      "9":"y",
      "10":"y",
      "11":"y"
    },
    "edge":{
      "12":"y",
      "13":"y",
      "14":"y"
    },
    "firefox":{
      "15":"y",
      "16":"y",
      "17":"y"
    }
 }

There is more data but this should give you an idea about the structure. This is my code:

var browsers = ["ie","edge","firefox"];

for (var i = 0; i < browsers.length; i++) {
  var bStats = result.stats.browsers[i];
  //Do something with it...
}

This gives me the error Uncaught TypeError: Cannot read property '0' of undefined. If I directly use result.stats.ie etc. everything works perfectly. How can I iterate through all this data properly?

Neena Vivek
  • 667
  • 7
  • 19

1 Answers1

1

You aren't looking for the property browser which contains an array : result.stats.browsers[i] but for a variable property name, which can be accessed with square bracket notation:

var bStats = result.stats[browsers[i]];

The snippet below should demonstrate this in practice:

var result = {
  "stats":{
    "ie":{
      "9":"y",
      "10":"y",
      "11":"y"
    },
    "edge":{
      "12":"y",
      "13":"y",
      "14":"y"
    },
    "firefox":{
      "15":"y",
      "16":"y",
      "17":"y"
    }
 }
 
 }
 
var browsers = ["ie","edge","firefox"];

for (var i = 0; i < browsers.length; i++) {
  var bStats = result.stats[browsers[i]];
  console.log(bStats);
}
 
Andrew Reid
  • 37,021
  • 7
  • 64
  • 83