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

如何在多层嵌套对象数组的指定位置插入新对象

嵌套数组对象中指定位置插入新元素的实现方案

问题背景

现有如下多层嵌套的JavaScript数组对象:

[
    {
        "id": "1709408412689",
        "name": "WB1",
        "children": [
            {
                "id": "1709408412690",
                "name": "WA X",
                "children": [
                    {
                        "id": "1709408412687",
                        "name": "B-Plan",
                        "children": []
                    },
                    {
                        "id": "1709408606635",
                        "name": "Lph 1",
                        "children": []
                    }
                ]
            },
            {
                "id": "1709408412691",
                "name": "WA 1",
                "children": [
                    {
                        "id": "1709408679357",
                        "name": "B-Plan",
                        "children": []
                    },
                    {
                        "id": "1709408679358",
                        "name": "Lph 1",
                        "children": []
                    },
                    {
                        "id": "1709408679359",
                        "name": "Lph 2",
                        "children": [
                            {
                                "id": "1709308679359",
                                "name": "Lph 2.2",
                                "children": []
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

给定插入参数:

{
    newID: 1509408679357,
    name: 'INSERTHERE',
    typeToInsert: 'before', // 可选值:before/after
    placeToInsert: '1709408679358'
}

需要在ID为1709408679358的对象前插入新对象,由于对象层级不固定,需用递归实现。

实现方案

核心思路是递归遍历每一层的children数组,找到目标ID所在的数组后,根据typeToInsert确定插入位置,完成插入后返回标识终止递归。

function insertNode(tree, insertParams) {
    const { newID, name, typeToInsert, placeToInsert } = insertParams;
    // 遍历当前层级的节点
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        // 检查当前节点是否是目标节点
        if (node.id === placeToInsert) {
            const newNode = {
                id: String(newID),
                name: name,
                children: []
            };
            // 根据插入类型确定位置
            const insertIndex = typeToInsert === 'before' ? i : i + 1;
            tree.splice(insertIndex, 0, newNode);
            // 找到目标并完成插入,返回true终止递归
            return true;
        }
        // 如果当前节点有子节点,递归遍历子节点
        if (node.children && node.children.length > 0) {
            const found = insertNode(node.children, insertParams);
            // 如果子节点中找到目标,直接返回true
            if (found) return true;
        }
    }
    // 当前层级未找到目标,返回false
    return false;
}

使用示例

// 原始嵌套数组
const originalTree = [/* 放入上述原始数组内容 */];
// 插入参数
const insertConfig = {
    newID: 1509408679357,
    name: 'INSERTHERE',
    typeToInsert: 'before',
    placeToInsert: '1709408679358'
};

// 执行插入操作
insertNode(originalTree, insertConfig);

// 输出结果(与预期一致)
console.log(JSON.stringify(originalTree, null, 4));

执行后得到的结果如下:

[
    {
        "id": "1709408412689",
        "name": "WB1",
        "children": [
            {
                "id": "1709408412690",
                "name": "WA X",
                "children": [
                    {
                        "id": "1709408412687",
                        "name": "B-Plan",
                        "children": []
                    },
                    {
                        "id": "1709408606635",
                        "name": "Lph 1",
                        "children": []
                    }
                ]
            },
            {
                "id": "1709408412691",
                "name": "WA 1",
                "children": [
                    {
                        "id": "1709408679357",
                        "name": "B-Plan",
                        "children": []
                    },
                    {
                        "id": "1509408679357",
                        "name": "INSERTHERE",
                        "children": []
                    },
                    {
                        "id": "1709408679358",
                        "name": "Lph 1",
                        "children": []
                    },
                    {
                        "id": "1709408679359",
                        "name": "Lph 2",
                        "children": [
                            {
                                "id": "1709308679359",
                                "name": "Lph 2.2",
                                "children": []
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

说明

  • 函数会直接修改传入的原始数组,如果需要保留原数组,可先使用深拷贝(如JSON.parse(JSON.stringify(originalTree)))复制一份再操作。
  • 递归过程中一旦找到目标节点完成插入,会立即返回true终止后续递归,提升效率。
  • 支持before和after两种插入位置类型,适配不同需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 16:15:57