crispEtomE crispEtomE - 10 days ago 4
Javascript Question

Finding the number of elements in a json object

I can't figure out how to find the number of elements contained in a JSON object with JavaScript. This is how my object is structured:

var shows = [];
//make http call here to api url and store in variable called 'data'
for (int i = 0; i < data.length; i++) {
var element = {
"location": {
"latitude": data[j].venue.latitude,
"longitude": data[j].venue.longitude
},
"artist": data[j].artists[0].name,
"venue_name": data[j].venue.name,
"date": data[j].datetime
};
shows.push(element);
};


So I can access the elements easily by using
shows[i].location
or whatever key I'd like access. However, all the question/answers that cover this topic seem to recommend
Object.keys(shows).length
to find the number of elements (I've also had trouble getting a for-each loop to work for this object of elements).

However, this doesn't work in my case (I'm assuming because 'shows' doesn't have any direct keys) so I was just wondering if there is any other way to access the number of elements (each with 4 key : value pairs) that are inside of "shows"? Or is there just another way to iterate over every element? Or if that is not possible is there another way I could structure my object to make it easier to find the number of elements? Any help is much appreciated!

Answer

Given

[A]ny other way to access the number of elements (each with 4 key : value pairs) that are inside of "shows".

The "number of elements" you are speaking of is the length of the array that you are pushing objects onto. The objects pushed each have four key-value pairs.

You would determine the number of elements (length of the array) using (or in an array):

var lengthOfShows = shows.length;
for (var i = 0; i < shows.length; i++) {
  var currentShow = shows[i];
  // references
  // shows[i].location
}

In your code ...

for (int i = 0; i < data.length; i++) {

Should be ...

for (var j = 0; j < data.length; j++) {

Since you are referencing data[j] inside the for-loop.