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

如何修改JS函数实现遍历嵌套product对象并在指定位置添加子产品

无限层级子产品插入函数修复方案

原有代码核心问题

  • 循环逻辑空转:没有对遍历指针做赋值更新,循环结束后仍然指向根节点,导致所有新元素都被插入到根层级
  • 冗余属性访问:无意义调用了不存在的listOfNewCustomProduct属性,会直接导致运行时报错
  • 缺少边界校验:没有处理遍历过程中某层级childProducts为空的场景,索引访问会直接报错

修复后代码

export const addChildProduct = (childTree, nestedChildIndex, updatedChild) => {
    // 直接修改原对象的版本,如需不可变更新可先深拷贝childTree
    let currentParent = childTree;
    // 遍历索引数组,定位到要插入子项的父级产品的childProducts数组
    for (let i = 0; i < nestedChildIndex.length; i++) {
        const index = Number(nestedChildIndex[i]);
        // 校验当前层级对应索引的子产品是否存在
        if (!currentParent[index]) {
            throw new Error(`嵌套路径 ${nestedChildIndex.slice(0, i+1).join('.')} 对应的子产品不存在`);
        }
        const currentProduct = currentParent[index];
        // 若当前产品没有childProducts则初始化空数组
        if (!currentProduct.childProducts) {
            currentProduct.childProducts = [];
        }
        // 指针移动到当前产品的childProducts数组,进入下一层遍历
        currentParent = currentProduct.childProducts;
    }
    // 插入新子项
    currentParent.push(updatedChild);
    return childTree;
};

逻辑说明

举个例子,当nestedChildIndex为['0', '0']时,循环执行两次:

  1. 第一次循环取索引0,拿到根数组的第0个产品,指针移动到该产品的childProducts数组
  2. 第二次循环取索引0,拿到上一层childProducts的第0个产品,指针移动到该产品的childProducts数组
  3. 循环结束,将新子项插入到该数组中,完成指定层级的插入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:36:02