如何修改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']时,循环执行两次:
- 第一次循环取索引0,拿到根数组的第0个产品,指针移动到该产品的
childProducts数组 - 第二次循环取索引0,拿到上一层
childProducts的第0个产品,指针移动到该产品的childProducts数组 - 循环结束,将新子项插入到该数组中,完成指定层级的插入
内容的提问来源于stack exchange,提问作者EshgheCode
相关产品推荐
相关产品推荐

