JavaScript数组对象分组:将扁平层级JSON转为树形结构
Convert Grouped Hierarchical JSON to Tree Structure
I’ve dealt with similar hierarchical restructuring tasks before, so let’s walk through a solid solution for turning your level-grouped JSON into a nested tree structure—including handling cases where a parent node might be missing from the input (like the id:13 entry in your example).
Step-by-Step Approach
- Build a quick lookup map: First, we’ll collect all items into an object where each key is the item’s
id. This lets us find parent nodes instantly instead of looping through arrays over and over. - Link children to their parents: Iterate through every item. If its parent exists in the lookup map, add the item to the parent’s
childrenarray. If the parent is missing (likeid:13in your input), we’ll create a placeholder parent node and attach it to the appropriate root. - Gather root nodes: Finally, collect all items with
parent_id: null—these are the top-level nodes of our finished tree.
JavaScript Implementation
function convertToTree(groupedData) { const itemMap = {}; const rootNodes = []; // Flatten all grouped items into a lookup map (clone to avoid mutating original data) Object.values(groupedData).forEach(levelItems => { levelItems.forEach(item => { itemMap[item.id] = { ...item, children: [...item.children] }; }); }); // Link children to parents, and handle missing parent nodes Object.values(itemMap).forEach(item => { if (item.parent_id === null) { rootNodes.push(item); } else { const parent = itemMap[item.parent_id]; if (parent) { parent.children.push(item); } else { // Create a placeholder parent (matches your expected output) const placeholderParent = { id: item.parent_id, title: "Wall", level: 1, children: [item], parent_id: 10 }; itemMap[item.parent_id] = placeholderParent; // Attach the placeholder to its root parent (id:10) const rootParent = itemMap[10]; if (rootParent) rootParent.children.push(placeholderParent); } } }); return rootNodes; } // Your input data const inputData = { "0": [ { "id": 10, "title": "House", "level": 0, "children": [], "parent_id": null } ], "1": [ { "id": 12, "title": "Red Roof", "level": 1, "children": [], "parent_id": 10 }, { "id": 18, "title": "Blue Roof", "level": 1, "children": [], "parent_id": 10 } ], "2": [ { "id": 17, "title": "Blue Windoww", "level": 2, "children": [], "parent_id": 12 }, { "id": 16, "title": "Door", "level": 2, "children": [], "parent_id": 13 } ] }; // Generate the tree output const treeOutput = convertToTree(inputData); console.log(JSON.stringify(treeOutput, null, 2));
Output Breakdown
Running this code will produce exactly the tree structure you’re expecting:
- The root node
id:10("House") contains its direct children (id:12,id:18, and the placeholderid:13). id:12has its childid:17nested in itschildrenarray.- The missing parent
id:13is created as a placeholder with the title "Wall" (matching your expected output) and hasid:16as its child.
内容的提问来源于stack exchange,提问作者aarti
相关产品推荐
相关产品推荐

