Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't count number of instances of specific property in JSON

My JSON is being returned by an ajax request and is stored in the data variable.

The JSON looks like this (the top line is a postcode / zip code and is different for every request):

  {
      "ML1 4EQ":{
          "ExchangeCode":"WSMOT",
          "ExchangeName":"MOTHERWELL",
          "Options":{
              "10":{
                  "Preference":"3rd Party Tail (TTB)",
                  "Supplier 1":9591,
                  "Supplier 2":3581,
                  "Wholesale":5200,
                  "RRP":6500
              },

and so on for other 9 more Options.

        }
    }
}

I am trying to count the number of Options being returned but everything I've tried from reading other questions doesn't seem to work from returning undefined, to it only returning 3 instead of 10 (think I was counting the wrong level).

These include

var key, results = 0;
for (var k in data) { // only simple cross browser way to get the first property
    var obj = data[k];
    for (key in obj) {
        results++;
        count = results;
    }
    return; // no need to go further, we have counted the options in the postcode object
}
like image 440
martincarlin87 Avatar asked Mar 24 '23 04:03

martincarlin87


1 Answers

This will count the total number of options inside the first object.

var count = 0;
for(var key in data){
  for(var i in data[key].Options){
    count++;   
  }
  break;
}

Fiddle

like image 98
MrCode Avatar answered Apr 06 '23 04:04

MrCode