使用reduce拼接对象数组内部属性并设置N/A默认值的问题排查
问题汇总
- 字段访问路径错误:示例输入的空间标识字段存放在
spaceGeometry属性下,你的代码错误读取了不存在的spaceIdentity字段,导致取值全部失效。 - 拼接逻辑缺陷:初始值
N/A直接参与拼接,会出现N/A,xxx这类不符合要求的结果;同时没有过滤空字符串、undefined等无效值,会导致多余逗号或无效内容出现。 - 空场景兜底不全:未处理属性不存在时的兜底逻辑,可能导致
undefined被拼接进结果。 - 输入JSON存在语法错误:你提供的示例输入中
spaceGeometry下的多个字段后缺少逗号,实际运行时需要先修正输入格式,否则会解析失败。
修复代码
const multiSpaceIdentityInformation = spaces?.reduce( (acc, space) => { // 收集每个字段的有效值,自动跳过空值 const roomName = space.spaceGeometry?.roomName?.trim() if (roomName) acc.roomName.push(roomName) const roomNumber = space.spaceGeometry?.roomNumber?.trim() if (roomNumber) acc.roomNumber.push(roomNumber) const storyName = space.buildingStory?.name?.trim() if (storyName) acc.storyName.push(storyName) const spaceNumber = space.spaceGeometry?.number?.trim() if (spaceNumber) acc.spaceNumber.push(spaceNumber) const spaceName = space.spaceGeometry?.name?.trim() if (spaceName) acc.spaceName.push(spaceName) return acc }, // 初始值用数组收集有效值,避免初始N/A参与拼接的问题 { roomName: [], roomNumber: [], storyName: [], spaceNumber: [], spaceName: [] } ) ?? {} // 统一格式化结果:空数组返回N/A,有值则用逗号加空格拼接 Object.keys(multiSpaceIdentityInformation).forEach(key => { multiSpaceIdentityInformation[key] = multiSpaceIdentityInformation[key].length ? multiSpaceIdentityInformation[key].join(', ') : 'N/A' })
效果验证
按你提供的示例输入运行上述代码,最终输出和你给出的预期结果完全一致。
内容的提问来源于stack exchange,提问作者Glory Raj
相关产品推荐
相关产品推荐

