如何获取JSON对象中的数组数量
问题描述:
以下是我的JSON。我想在这个对象中获得数组和数组的名称。这是动态创建的,所以我不知道它的数量和名称。这里是这个例子中的2个数组,名为Table和Table1。如何获取JSON对象中的数组数量
"{
"Table": [
{
"Day": "Jan",
"Counts": 20,
"SrNo": 1,
"Title": "test2",
"ProfilePic": "/Image1.jpg"
},
{
"Day": "Feb",
"Counts": 10,
"SrNo": 2,
"Title": "test2",
"ProfilePic": "/Image1.jpg"
}
],
"Table1": [
{
"Day": "01",
"Counts": 5,
"SrNo": 1,
"Title": "test3",
"ProfilePic": "/Image2.jpg"
},
{
"Day": "02",
"Counts": 9,
"SrNo": 2,
"Title": "test3",
"ProfilePic": "/Image2.jpg",
}
]
}"
答
尝试以下提到的代码,
Object.keys(jsonObject).length;
另请参阅...:Get total number of items on Json object?
要获得所有的名字:
var keys = Object.keys(jsonObject); // this will return root level title ["Table" , "Table1"]
答
假设每属性在对象包含数组,你可以指望使用Object.keys
属性的数量,就像这样:
var arrayCount = Object.keys(obj).length;
或者,如果你真的想确定属性的类型,如果有一些其他类型的对象时,你会需要遍历并逐个检查每个属性,这可以使用filter()
这样进行:
var obj = {
"Table": [{
"Day": "Jan",
"Counts": 20,
"SrNo": 1,
"Title": "test2",
"ProfilePic": "/Image1.jpg"
},
{
"Day": "Feb",
"Counts": 10,
"SrNo": 2,
"Title": "test2",
"ProfilePic": "/Image1.jpg"
}
],
"Table1": [{
"Day": "01",
"Counts": 5,
"SrNo": 1,
"Title": "test3",
"ProfilePic": "/Image2.jpg"
},
{
"Day": "02",
"Counts": 9,
"SrNo": 2,
"Title": "test3",
"ProfilePic": "/Image2.jpg",
}
],
'NotArray1': 'foo', // < not an array
'isArray': false // < not an array
}
var arrayCount = Object.keys(obj).filter(function(key) {
return obj[key].constructor === Array;
}).length;
console.log(arrayCount);
+0
谢谢你的帮助@Rory .. –
答
呦ü可以使用Array.prototype.reduce(),以总回报均是有效的数组对象的属性值:
var obj = {
"Table": [{
"Day": "Jan",
"Counts": 20,
"SrNo": 1,
"Title": "test2",
"ProfilePic": "/Image1.jpg"
}, {
"Day": "Feb",
"Counts": 10,
"SrNo": 2,
"Title": "test2",
"ProfilePic": "/Image1.jpg"
}],
"Table1": [{
"Day": "01",
"Counts": 5,
"SrNo": 1,
"Title": "test3",
"ProfilePic": "/Image2.jpg"
}, {
"Day": "02",
"Counts": 9,
"SrNo": 2,
"Title": "test3",
"ProfilePic": "/Image2.jpg"
}
],
"Table2": false
},
arrayCount = Object.keys(obj).reduce(function (acc, val) {
return Array.isArray(obj[val]) ? ++acc : acc;
}, 0);
console.log(arrayCount);
+0
谢谢@Yosvel .. –
能够保证所有的阵列将只对第一个“级别”,并不是嵌套对象? – Phillip
感谢您的答案,我的情况我需要json.stringify即,Object.keys(JSON.parse(obj))。length; –
[获取Json对象上的项目总数?](https://stackoverflow.com/questions/13782698/get-total-number-of-items-on-json-object) –