JS基于对象数组生成指定结构新数组时无法合并多状态如何解决
问题根源
你当前的写法里,flatMap会把同一条原始数据里的多个result项拆成独立的多条数据,后续reduce直接对每条数据执行push操作,所以同个timestamp下的多个result项会生成多个独立对象,无法合并到同一个对象里。
最优解决方案
直接遍历原始数组的每条数据,单条数据内处理result字段的聚合即可,不需要额外做扁平化处理,代码更简洁性能也更高:
const chartData = data.map(item => { // 初始化输出对象,所有状态默认赋值为0 const outputItem = { timestamp: item.timestamp, "Not Covered": 0, "Active": 0, "Expiring Soon": 0 } // 遍历当前条目的所有result项,给对应状态赋值 item.result.forEach(({ label, value }) => { if (outputItem.hasOwnProperty(label)) { outputItem[label] = value } }) return outputItem })
保留flatMap+reduce写法的调整方案
如果你需要保留现有写法的结构,就需要把reduce的累加容器改成对象,用timestamp做键做分组聚合,最后再转成数组即可:
let flattenedResult = data.flatMap(({result,...r}) => result.map(o => ({ ...o,...r}))); const chartData = Object.values(flattenedResult.reduce((acc, item) => { const {timestamp, value, label} = item; // 同时间戳的条目不存在时先初始化 if (!acc[timestamp]) { acc[timestamp] = { timestamp, "Not Covered": 0, "Active": 0, "Expiring Soon": 0 } } // 给对应状态赋值 if (acc[timestamp].hasOwnProperty(label)) { acc[timestamp][label] = value } return acc; }, {}));
内容的提问来源于stack exchange,提问作者AlexUA
相关产品推荐
相关产品推荐

