最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get number of rows of multidimensional JSON variable - Stack Overflow

programmeradmin2浏览0评论

I have a PHP function that returns a multiple-level JSON object in the format

var data = {
  1 : { 
    1: { Object },
    2: { Object },
     ...,
     ...
  }, 
  2: {
    1: { Object },
    2: { Object },
    ...,
    ...
  }
}

I need to get the length of data to initialize a for loop maximum value. By this, I mean the count of the first level entries.

data[1].length returns 22, and data[2].length returns 23 via the console.log printout. This is expected, but data.length returns undefined.

Is there a better method than

var count = 0;

for (var i=1; i< Number.MAX_VALUE; i++){
  if (typeof data[i] != 'undefined')
    count = i;
}

I have a PHP function that returns a multiple-level JSON object in the format

var data = {
  1 : { 
    1: { Object },
    2: { Object },
     ...,
     ...
  }, 
  2: {
    1: { Object },
    2: { Object },
    ...,
    ...
  }
}

I need to get the length of data to initialize a for loop maximum value. By this, I mean the count of the first level entries.

data[1].length returns 22, and data[2].length returns 23 via the console.log printout. This is expected, but data.length returns undefined.

Is there a better method than

var count = 0;

for (var i=1; i< Number.MAX_VALUE; i++){
  if (typeof data[i] != 'undefined')
    count = i;
}
Share Improve this question asked Aug 30, 2012 at 16:30 JasonJason 11.4k22 gold badges93 silver badges185 bronze badges 2
  • is there any way you can store your data in an array of objects instead of an object? – dm03514 Commented Aug 30, 2012 at 16:33
  • I really don't have control over that part at this time, unfortunately. – Jason Commented Aug 30, 2012 at 16:38
Add a ment  | 

4 Answers 4

Reset to default 3

How About

Object.keys(data).length

If you can control the JSON format, nested arrays seem a better alternative.

If not, you can run something like

var length = 0;
for (var i in data) {
    if (isFinite(i) && i > length)
        length = i;
}

You can count the number of entries in a loop, like this:

var length = 0;
for (var key in data) {
  if (data.hasOwnProperty(key)) {
    length++;
  }
}

However, if you have control over the returned data, it would probably be easier to return an array instead of an object because the array will already have the length property you want.

Why not just do this instead of assigning numeric properties? Arrays will have the length property you wish:

var data = [
  [ 
    { Object },
    { Object },
     ...,
     ...
  ], 
  [
    { Object },
    { Object },
    ...,
    ...
  ]
]
发布评论

评论列表(0)

  1. 暂无评论