I apologize for the vague question. Hopefully my example adds some clarity to my question... So I have a hierarchical data structure like this:
var Company = {
root: {
title: 'CEO',
employees: [{
title: 'Vice President',
employees: [{
title: 'Sales Lead'
}, {
title: 'Marketing Lead'
}]
}]
}
};
My question is how would I find out the total number of employees in the root object? Visually, one can see that there are 3 employees in the company. I am working with recursion to try and solve this problem, but I just can't seem to get it working right... or working at all for that matter. I appreciate any help, tips, or advice :)
You can use .reduce
with a named function that can be called recursively. The base case would be if an object has no employees.
const totalEmployees = Company.root.employees.reduce(countEmployees, 0);
function countEmployees(prev, next) {
// count *this* employee
let sum = prev + 1;
if (next.employees && next.employees.length) {
// count any nested employees
sum += next.employees.reduce(countEmployees, 0);
}
return sum;
}
You can use a recursive function to loop though a nested object structure.
Here is how you do it.
function countEmployee(root){
if(!root.employees){
return 0;
}
var numOfEmployee = root.employees.length;;
var count = 0;
for(var i=0; i<numOfEmployee; i++){
count = count + countEmployee(root.employees[i]);
}
numOfEmployee = numOfEmployee + count;
return numOfEmployee;
}
countEmployee(Company.root); //return 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.