Extracting data from Nested Map using Recursion
Sat May 04 2024
Map and Recursion:
The getAllEmployeeNames function maps over each department, collecting the names of employees. For departments with subdepartments, the function recursively calls itself, ensuring all nested structures are processed.
FlatMap:
Another approach leverages flatMap to streamline the extraction process, concatenating employee names from both the main departments and their subdepartments in a single step.
1//map method to generate an array of all employee names across all departments and subdepartments of the company object
2const company = {
3    name: "Tech Solutions",
4    departments: [
5        {
6            name: "Engineering",
7            employees: [
8                { name: "Alice", role: "Software Engineer" },
9                { name: "Bob", role: "DevOps Engineer" }
10            ],
11            subdepartments: [
12                {
13                    name: "Quality Assurance",
14                    employees: [
15                        { name: "Charlie", role: "QA Engineer" }
16                    ],
17                    subdepartments: []
18                }
19            ]
20        },
21        {
22            name: "Human Resources",
23            employees: [
24                { name: "David", role: "Recruiter" },
25                { name: "Eve", role: "Benefits Coordinator" }
26            ],
27            subdepartments: []
28        }
29    ]
30};
31
32
33function getAllEmployeeNames(departments){
34    return departments.map(department => {
35        let names = department.employees.map(employee => employee.name);
36        if (department.subdepartments && department.subdepartments.length > 0) {
37            department.subdepartments.forEach(subdepartment => {
38                names = names.concat(getAllEmployeeNames([subdepartment]));
39            });
40        }
41        return names;
42    }).flat();
43}
44
45let mappedarr = company.departments.flatMap(item => { 
46    let totalItem = [...item.employees.map(item => item.name),...item.subdepartments.flatMap(item => item.employees.map(item => item.name))]
47    return totalItem
48})
49
50
51
52const employeeNames = getAllEmployeeNames(company.departments);
53console.log(employeeNames);
54console.log("mappedarr==>",mappedarr)