Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
91
rated 0 times [  92] [ 1]  / answers: 1 / hits: 24677  / 14 Years ago, tue, december 28, 2010, 12:00:00

I have a Json like this
{0:{parent_id:1649,id:1803,last_update_on:2010-12-24 07:01:49,message:dhb;lxd,created_by_id:21,created_by_name:Amol Deshpande}}.
So ideally i should get length as 1 considering i have only 1 value on 0th location.



what if i have a JSON like this



{0:{parent_id:1649,id:1803,last_update_on:2010-12-24 07:01:49,message:dhb;lxd,created_by_id:21,created_by_name:Amol Deshpande},1:{parent_id:1649,id:1804,last_update_on:2010-12-24 07:02:49,message:amol,created_by_id:21,created_by_name:Amol Deshpande}}


I am getting the value as undefined if i do alert(response.length); where response is my JSON as mentioned above



Any suggestions?


More From » jquery

 Answers
20

Objects don't have a .length property...not in the way you're thinking (it's undefined), it's Arrays that have that, to get a length, you need to count the keys, for example:


var length = 0;
for(var k in obj) if(obj.hasOwnProperty(k)) length++;

Or, alternatively, use the keys collection available on most browsers:


var length = obj.keys.length;

MDN provides an implementation for browsers that don't already have .keys:


Object.keys = Object.keys || function(o) {
var result = [];
for(var name in o) {
if (o.hasOwnProperty(name))
result.push(name);
}
return result;
};

Or, option #3, actually make your JSON an array, since those keys don't seem to mean much, like this:


[{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"},{"parent_id":1649,"id":"1804","last_update_on":"2010-12-24 07:02:49","message":"amol","created_by_id":"21","created_by_name":"Amol Deshpande"}]

Then you can use .length like you want, and still access the members by index.


[#94466] Sunday, December 26, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marinal

Total Points: 655
Total Questions: 99
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;