如何合并相同selectionId的数组对象并保留全部topicName
解决方案
问题说明
原有代码通过Object.assign直接覆盖同selectionId对应对象的属性,因此只能保留最后一个topicName值。另外你给出的预期输出结构不符合JS对象语法规范:对象不能直接包含["topicName":"xxx",...]这种结构,建议统一将topicName字段设为数组类型,后续循环逻辑无需额外兼容字段类型,使用更便捷。
实现代码
方案1:统一topicName为数组类型(推荐)
const result = Object.values( list.reduce((accumulator, current) => { const id = current.selectionId if (!accumulator[id]) { accumulator[id] = { selectionId: id, topicName: [current.topicName] } } else { accumulator[id].topicName.push(current.topicName) } return accumulator }, {}) )
输出结果
[ { "selectionId": 1, "topicName": ["topic created or not validate", "hghhhg test test"] }, { "selectionId": 2, "topicName": ["topic test"] }, { "selectionId": 3, "topicName": ["new topic for test topic name and description name(test check)"] }, { "selectionId": 4, "topicName": ["topic check check", "topic check popup"] }, { "selectionId": 5, "topicName": ["test"] } ]
方案2:兼容单个topicName为字符串类型
如果需要严格匹配你预期的结构,即单个值为字符串、多个值才为数组,可以用以下实现:
const result = Object.values( list.reduce((accumulator, current) => { const id = current.selectionId if (!accumulator[id]) { accumulator[id] = { selectionId: id, topicName: current.topicName } } else { if (!Array.isArray(accumulator[id].topicName)) { accumulator[id].topicName = [accumulator[id].topicName] } accumulator[id].topicName.push(current.topicName) } return accumulator }, {}) )
输出结果
[ { "selectionId": 1, "topicName": ["topic created or not validate", "hghhhg test test"] }, { "selectionId": 2, "topicName": "topic test" }, { "selectionId": 3, "topicName": "new topic for test topic name and description name(test check)" }, { "selectionId": 4, "topicName": ["topic check check", "topic check popup"] }, { "selectionId": 5, "topicName": "test" } ]
内容的提问来源于stack exchange,提问作者nihar
相关产品推荐
相关产品推荐

