JavaScript重构带子节点的对象数组:将父级属性嵌入子项列表
数组结构转换方案
该需求完全可实现,核心逻辑为遍历所有门店节点,将门店公共属性合并到其下属每个电脑商品对象中,最终汇总为一维扁平数组即可,以下是几种常用的实现方式:
方案1:flatMap 最简实现(推荐,ES2019+ 支持)
flatMap 会先对数组每个元素执行映射操作,再将映射返回的子数组自动拍平一层,完美适配当前一层嵌套的场景,代码最简洁:
const flattenedList = accessories.flatMap(store => { return store.computers.map(item => ({ storeid: store.storeid, storename: store.storename, ...item })) })
方案2:reduce 兼容实现
如果需要兼容不支持flatMap的老旧运行环境,可以用reduce实现相同逻辑:
const flattenedList = accessories.reduce((res, store) => { const computerList = store.computers.map(item => ({ storeid: store.storeid, storename: store.storename, ...item })) return res.concat(computerList) }, [])
方案3:嵌套循环基础实现
逻辑最直观,无任何API兼容问题,适合新手理解:
const flattenedList = [] for (const store of accessories) { for (const computer of store.computers) { flattenedList.push({ storeid: store.storeid, storename: store.storename, ...computer }) } }
注意:以上三种实现均不会修改原始输入数组和内部对象,返回的是全新构造的结果数组,无原始数据污染风险。如果需要覆盖原变量,直接将结果赋值给原变量即可:
accessories = flattenedList
内容的提问来源于stack exchange,提问作者Gabriel Jonah
相关产品推荐
相关产品推荐

