Unable to count the number of instances of a specific property in JSON

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

JSON looks like this (the top line is a zip / postal code and is different for each request):

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

etc. for the other 9 more Options .

  } } } 

I am trying to count the number of Options returned, but everything I tried to read other questions does not seem to return from the returned undefined, it returns 3 instead of 10 (I think I considered 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 } 
+4
source share
2 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

+6
source

Counting the number of properties in an Object not completely simple. There is no property that will tell you directly, and if you for...in count them over them, you will also get inherited properties, so if someone defines something on Object.prototype , you will get the wrong answer.

In ECMAScript Fifth Edition, you get getOwnPropertyNames , which returns an array of non-inherited property names:

 var options= {'1': 'a', '2': 'b'}; Object.getOwnPropertyNames(options).length; // 2 

For browsers that do not yet support Fifth Edition (primarily IE <= 8), you can pin it:

 if (!('getOwnPropertyNames' in Object)) { Object.getOwnPropertyNames= function(o) { var names= []; for (var k in o) if (Object.hasOwnProperty(k)) names.push(k); return names; }; } 

However, if you have control over the JSON output format, I would strongly suggest turning your Options object into a simple array, which would seem to be much better modeling of your data. With an array, you can just use Options.length .

+1
source

Source: https://habr.com/ru/post/1491592/


All Articles