[英]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. 我不知道如何用JavaScript查找JSON对象中包含的元素数量。 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. 因此,我可以通过使用
shows[i].location
或我想要访问的任何键来轻松访问元素。 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). 但是,涉及该主题的所有问题/答案似乎都建议使用
Object.keys(shows).length
来查找元素的数量(我也很难让for-each循环适用于此元素对象)。
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"? 但是,这在我的情况下不起作用(我假设是因为'shows'没有任何直接键),所以我只是想知道是否还有其他方法可以访问元素数量(每个元素都有4个键:值对”)? 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!
任何帮助深表感谢!
Given 给定
[A]ny other way to access the number of elements (each with 4 key : value pairs) that are inside of "shows".
[显示]访问“显示”中的元素数量(每个带有4个键:值对)的其他方法。
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. 由于您要在for循环内引用data [j]。
From your code, shows
is an array. 在您的代码中,
shows
是一个数组。 Arrays have a length property. 数组具有length属性。
shows.length
is probably what you need. 可能正是您所需要的。 Looks like it would be the same as
data.length
and that data is probably also an array. 看起来它将与
data.length
相同,并且该数据可能也是一个数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.