如何递归映射并扁平化多维对象数组,为子元素添加Supervisor关联
Got it, let's fix this properly! Your current code only handles two fixed levels, which is why it can't process deeper nested nodes like the "Development" department and its children. We need a recursive approach that can traverse any depth of the tree and add the supervisor field correctly for every node.
The Problem with Your Current Code
- It manually handles only level 1 and level 2 children, so it breaks for deeper hierarchies.
- It modifies the original
props.dataarray directly, which can cause unintended side effects in your application.
Recursive Solution
Here's a function that will flatten your nested structure completely, no matter how many levels deep it goes:
function flattenUsers(nodes, supervisor = null) { const flattened = []; for (const node of nodes) { // Create a copy of the node to avoid mutating the original data const processedNode = {...node}; // Add supervisor field if there's a parent if (supervisor !== null) { processedNode.supervisor = supervisor; } // Remove children from the current node (we'll process them separately) delete processedNode.children; // Add the processed node to our result array flattened.push(processedNode); // Recursively process children if they exist if (node.children && node.children.length > 0) { flattened.push(...flattenUsers(node.children, node.label)); } } return flattened; } // Usage with your UsersData const flattenedResult = flattenUsers(UsersData.data); console.log(flattenedResult);
How This Works
Recursive Traversal: The function takes a list of nodes and an optional
supervisor(the parent's label). For each node:- We create a copy of the node to avoid altering the original data.
- If a supervisor exists, we add the
supervisorfield to the copied node. - We remove the
childrenproperty from the copied node (since we'll process each child as a separate entry in the flat array). - We add the processed node to our result.
- If the node has children, we recursively call the function on those children, passing the current node's label as their supervisor, and append the result to our flat array.
Handles All Depths: This approach works for any number of nested levels—whether it's 2, 3, or 10 levels deep, it will traverse every node and assign the correct supervisor.
No Side Effects: By creating copies of each node instead of modifying the original data, we avoid unexpected changes to your source
UsersData.
Example Output
The output will exactly match what you requested:
- The CEO node has no
supervisorfield. - CFO/COO/CTO have
supervisor: "CEO". - Tax/Legal have
supervisor: "CFO". - Development's children (Analysis/Front End/Back End) have
supervisor: "Development", and so on.
内容的提问来源于stack exchange,提问作者Daniel H.

