如何对JS对象数组按tableName去重并合并重复项的tableFooter值
实现方案
你可以用 Array.prototype.reduce 配合 Object.values 实现,不需要手动写for循环:
const newTable = Object.values( arrTable.reduce((acc, cur) => { const existed = acc[cur.tableName] if (existed) { existed.tableFooter += ` ${cur.tableFooter}` } else { // 用扩展运算符拷贝避免修改原数组对象,不需要的话也可以直接写acc[cur.tableName] = cur acc[cur.tableName] = {...cur } } return acc }, {}) )
说明
- 逻辑是先把数组转成以
tableName为键的对象,分组的同时拼接重复项的tableFooter - 最后用
Object.values把对象的值提取成数组,刚好符合你要的输出格式 - 如果你业务里相同
tableName对应的tableDesc可能不一样,默认会保留第一个出现的项的tableDesc,和你给出的示例预期一致。
内容的提问来源于stack exchange,提问作者stuckonhtml
相关产品推荐
相关产品推荐

