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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With