This question already has an answer here:
这个问题在这里已有答案:
- How to efficiently count the number of keys/properties of an object in JavaScript? 19 answers
如何有效地计算JavaScript中对象的键/属性数? 19个答案
I have JSON which looks like this:
我有JSON,看起来像这样:
{
"item1": {
"category": "fruit",
},
"item2": {
"category": "fruit",
}
}
How can I count the no. of items inside this?
我怎么能算不上。这里面的物品?
1 个解决方案
#1
0
As in your JSON, number of items are the number of keys. Thus, get your JSON in an variable (say obj) and use the following:
与您的JSON一样,项目数是键的数量。因此,在变量(例如obj)中获取JSON并使用以下内容:
var obj = JSON.parse('{"item1":{"category":"fruit",},"item2":{"category":"fruit",}}');
Object.keys(obj).length;
#1
0
As in your JSON, number of items are the number of keys. Thus, get your JSON in an variable (say obj) and use the following:
与您的JSON一样,项目数是键的数量。因此,在变量(例如obj)中获取JSON并使用以下内容:
var obj = JSON.parse('{"item1":{"category":"fruit",},"item2":{"category":"fruit",}}');
Object.keys(obj).length;