jQuery 获取 Json 对象的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22580223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Length Of Json object
提问by droidev
I have json object which is returned from php file, the json values are as follows
我有一个从 php 文件返回的 json 对象,json 值如下
{
"0": {
"id": "35",
"name": "first name",
"date": "2014-03-03",
"age": "25"
},
"1": {
"id": "36",
"name": "name",
"date": "0000-00-00",
"age": "25"
},
"2": {
"id": "37",
"name": "myname",
"date": "0000-00-00",
"age": "25"
},
"average_age": 25,
"count": 3
}
How do I get the count of values other than average_age and count that is for the given json object i want to get 3 as length in jQuery
我如何获得除average_age以外的值的计数和给定json对象的计数,我想在jQuery中获得3作为长度
回答by droidev
I have got the answer
我有答案
Object.keys(result).length // returns 5
UPDATE
更新
From the comment this does not work on IE 7 and 8
根据评论,这不适用于 IE 7 和 8
回答by John S
Try:
尝试:
var count = 0;
while (obj[count]) {
count++;
}
回答by kol
To "get the count of values other than average_age
and count
", you can do something like this:
要“获取average_age
和count
”以外的值的计数,您可以执行以下操作:
function getCount(obj) {
var count = 0,
prop;
for (prop in obj) {
if (obj.hasOwnProperty(prop) && prop !== "average_age" && prop !== "count") {
count += 1;
}
}
return count;
}
var str = '{"0":{"id":"35","name":"Ahamed shajeer","date":"2014-03-03","age":"25"},"1":{"id":"36","name":"Meshajeer","date":"0000-00-00","age":"25"},"2":{"id":"37","name":"Iam shajeer","date":"0000-00-00","age":"25"},"average_age":25,"count":3}',
obj = JSON.parse(str);
console.clear;
console.log(getCount(obj));
Result:
结果:
3
You don't need jQuery. Anyway, why don't you want to use the count
field directly?
你不需要jQuery。无论如何,您为什么不想count
直接使用该字段?
回答by Gustavo Gutiérrez
This way worked for me:
这种方式对我有用:
var jsonObject= JSON.stringify(response); var count = JSON.parse(jsonObject).length;
var jsonObject= JSON.stringify(response); var count = JSON.parse(jsonObject).length;