Вы можете посчитать все элементы с помощью рекурсивного function
, который использует простой .forEach()
вызов по заданному array
.
. Вот как должен быть ваш код:
var items = 0;
function countItems(arr) {
arr.forEach(a => {
items += 1;
if (a.childs)
countItems(a.childs);
});
}
countItems(data.details);
Демо:
var data = {
"sec": "11",
"details": [{
"id": "1",
"user": "Me1"
},
{
"id": "2",
"uesr": "Me2",
"childs": [{
"id": "4",
"user": "Me4",
"parentID": "2"
},
{
"id": "6",
"user": "Me6",
"parentID": "2"
}
]
},
{
"id": "3",
"user": "Me3"
},
{
"id": "5",
"uesr": "Me5"
},
{
"id": "7",
"user": "Me7",
"childs": [{
"id": "8",
"uesr": "Me8",
"parentID": "7"
},
{
"id": "9",
"user": "Me9",
"parentID": "7"
}
]
}
],
"isDisplay": "true"
};
var items = 0;
function countItems(arr) {
arr.forEach(a => {
items += 1;
if (a.childs)
countItems(a.childs);
});
}
countItems(data.details);
console.log(items);