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

如何将对象数组中嵌套的子数组合并为单一数组?Reduce报错求解

解决嵌套parts数组合并的问题

嘿,我来帮你搞定这个reduce报错的问题!你遇到的Cannot read property concat of undefined错误,根源在于没有给reduce设置初始值。

错误原因分析

你写的代码arr.reduce((a,b) => a.parts.concat(b.parts)),第一次迭代时,a是数组的第一个对象(也就是{ location: 'somewhere', ... }),这时候a.parts是有效的数组,能和b.parts正常concat。但第二次迭代时,a变成了第一次concat后的结果(也就是一个parts数组),这时候a.parts就不存在了,自然会抛出undefined的错误。

正确的reduce写法

给reduce加上初始值(空数组[]),让累加器acc从空数组开始,每次把当前对象的parts合并进去:

const mergedParts = arr.reduce((acc, curr) => acc.concat(curr.parts), []);

这样每次迭代时,acc都是一个数组,调用concat就不会有问题了。用你的示例数组测试,会得到你想要的结果:

// 输入
const arr = [ 
  { location: 'somewhere', location_id: 1, parts: [ { part_id: 1, description: 'foo', qty: 1 } ] },
  { location: 'elsewhere', location_id: 2, parts: [ { part_id: 2, description: 'bar', qty: 1 } ] }
];

// 输出
[ { part_id: 1, description: 'foo', qty: 1 }, { part_id: 2, description: 'bar', qty: 1 } ]

更简洁的替代方案:flatMap

如果你用的是ES6及以上的环境,flatMap是更直观的选择——它先对每个元素执行映射(提取parts),再自动扁平化一层数组:

const mergedParts = arr.flatMap(item => item.parts);

这个写法更简洁,可读性也更高,效果和reduce版本完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:59:24