You need to enable JavaScript to run this app. Angular实现对象数组指定属性去重分组 按modelName渲染列表
优惠活动
大模型
产品
解决方案
定价
更多

Angular实现对象数组指定属性去重分组 按modelName渲染列表

按 modelName 合并分组的实现方案

不需要依赖Observable做复杂的筛选匹配,通过原生数组的聚合逻辑就能完成分组合并,以下是两个可直接落地的实现方案,适配不同的代码现状:

场景1:基于原始 packages 数组直接分组,避免产生冗余拆分结构

你之前通过forEach生成的拆分后结构存在重复的modelname条目,其实可以直接跳过这个拆分步骤,用原生Array.reduce对原始数组做一次性聚合,直接得到合并后的分组结构:

const groupedResult = packages.reduce((groupList, currentPkg) => {
  // 查找当前条目所属的分组是否已存在
  const matchedGroup = groupList.find(item => item.modelname === currentPkg.modelName)
  if (matchedGroup) {
    // 已存在分组则把当前套餐推入对应子数组
    matchedGroup.model.push({
      name: currentPkg.name,
      price: currentPkg.price
    })
  } else {
    // 未存在则新建独立分组
    groupList.push({
      modelname: currentPkg.modelName,
      model: [{
        name: currentPkg.name,
        price: currentPkg.price
      }]
    })
  }
  return groupList
}, [])

运行上述代码后,groupedResult会直接生成3个不重复的分组条目,每个分组下的model数组存储了该分组对应的所有套餐信息,无重复的modelname字段。

场景2:已生成拆分后的 packagesResult 结构,做二次合并

如果你已经拿到了之前生成的、每个分组仅存单个套餐的拆分后packagesResult数组,同样可以用reduce做二次聚合合并:

const mergedGroup = packagesResult.reduce((acc, currentItem) => {
  // 匹配相同modelname的已有分组
  const targetGroup = acc.find(item => item.modelname === currentItem.modelname)
  if (targetGroup) {
    // 合并子数组内容
    targetGroup.model = targetGroup.model.concat(currentItem.model)
  } else {
    acc.push({...currentItem})
  }
  return acc
}, [])

最终展示效果生成

拿到合并后的分组数据后,简单拼接文本就能达到预期的展示效果:

const outputText = mergedGroup.map(group => {
  // 把套餐格式转为「名称 (价格)」格式,用顿号拼接
  const pkgContent = group.model.map(pkg => `${pkg.name} (${pkg.price})`).join('、')
  return `${group.modelname}\n${pkgContent}`
}).join('\n\n')

outputText的最终输出和预期效果完全一致:

flatRate
Enterprise ($150)、Gold ($190)

usageBased
Enterprise ($50)

userBased
Extreme ($50)


内容的提问来源于stack exchange,提问作者String Name

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.28 21:24:04