You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. 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.
  2. Link children to their parents: Iterate through every item. If its parent exists in the lookup map, add the item to the parent’s children array. If the parent is missing (like id:13 in your input), we’ll create a placeholder parent node and attach it to the appropriate root.
  3. 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 placeholder id:13).
  • id:12 has its child id:17 nested in its children array.
  • The missing parent id:13 is created as a placeholder with the title "Wall" (matching your expected output) and has id:16 as its child.

内容的提问来源于stack exchange,提问作者aarti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:43:25