How to get the number of arrays in a JSON object
Below is my JSON. I want to get the number and name of an array in this object. This is dynamically created, so I don't know about its number and name (s). This example presents 2 arrays named Table and Table1.
"{
"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",
}
]
}"
source to share
Try the below code,
Object.keys(jsonObject).length;
Also reference ...: Get the total number of elements on a Json object?
To get all names:
var keys = Object.keys(jsonObject); // this will return root level title ["Table" , "Table1"]
source to share
Assuming each property in the object contains an array, you can simply count the number of properties with Object.keys
, for example:
var arrayCount = Object.keys(obj).length;
Alternatively, if you really want to determine the type of the property, in case there are any other types in the object, you will need to loop through and check each property separately, which can be done with the filter()
following:
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);
source to share
You can use Array.prototype.reduce () to return the total of all property values โโof an object that are a valid array:
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);
source to share