Count Objects In Array Big Data
hi how can i count how many objects are in this Object of arrays? In the children objects there are also Arrays with Objects. Dont really easy to understand... Hi looked at stackov
Solution 1:
Using ES2015:
constcount = (item) => 1 + (item.children || []).map(count).reduce((a, b) => a + b, 0)
count(DATA) //=> 252
Solution 2:
Use recursion.
functioncountObjects(obj) {
// the current element is an object +1
count = 1;
// check if object has childrenif (Array.isArray(obj.children)) {
// loop through children
obj.children.forEach(child => {
// count # of objects within each child and tally
count += countObjects(child)
});
}
return count;
}
console.log(countObjects(DATA));
(I ended up with 252
which is the number of {
)
Post a Comment for "Count Objects In Array Big Data"