如何清晰实现嵌套数组操作,优化多层嵌套map的冗余写法
嵌套数组操作可读性优化方案
优化思路
你已经引入了Immer,不需要用map做不可变更新,完全可以把嵌套的三元判断拆成逐层查找的独立步骤,避免嵌套地狱,逻辑一目了然。
优化后代码示例
以修改fList中id为51的对象为例,写法如下:
import { produce } from 'immer' // 入参:原始数组、要修改的层级id、要更新的f对象属性 const updateFItem = (originArr, pId, bId, fId, updateProps) => { return produce(originArr, draft => { // 1. 查找外层p对象 const targetP = draft.find(p => p.id === pId) if (!targetP) return // 2. 查找中层b对象 const targetB = targetP.bList.find(b => b.id === bId) if (!targetB) return // 3. 查找内层f对象 const targetF = targetB.fList.find(f => f.id === fId) if (!targetF) return // 4. 执行修改操作(你原来的"magic happens here"逻辑写在这里) Object.assign(targetF, updateProps) // 若要执行删除操作,替换上面的步骤4即可: // const fIndex = targetB.fList.findIndex(f => f.id === fId) // if (fIndex > -1) targetB.fList.splice(fIndex, 1) // 若要执行新增f对象操作,替换步骤4即可: // targetB.fList.push(newFItem) }) } // 调用示例:修改id为51的f对象,新增name字段为"测试" const newArr = updateFItem(arr, 123, 24, 51, { name: '测试' })
优势说明
- 逻辑完全扁平化,没有嵌套三元和多层map,每一步的操作意图清晰,后续维护的人一眼就能看懂每一步在做什么
- 每层都加了非空判断,避免找不到对应项时报错,鲁棒性更强
- 可扩展性高,需要修改、删除、新增任意层级的项时,只需要调整对应步骤的逻辑即可
- 可以把按id查找数组项的逻辑抽成公共工具函数复用,进一步简化代码:
// 公共工具函数,所有数组按id查找都可以用 const findById = (list, targetId) => list?.find(item => item.id === targetId) // 简化后的查找逻辑 const targetP = findById(draft, pId) const targetB = findById(targetP?.bList, bId) const targetF = findById(targetB?.fList, fId)
内容的提问来源于stack exchange,提问作者joputy
相关产品推荐
相关产品推荐

