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

如何按分类名称对产品对象数组进行合并分组展示

实现思路

  1. 先对原始对象数组按category字段分组,将同分类下的产品名称归集到同一数组中
  2. 遍历分组后的数据,先输出分类名称,再缩进输出该分类下的所有产品名

JS 实现代码

原始数据:

const productList = [
  {id: 1, name: 'Apple', category: 'Fruit'},
  {id: 2, name: 'Melon', category: 'Fruit'},
  {id: 3, name: 'iPhone', category: 'Phone'},
  {id: 4, name: 'Samsung Galaxy Note 8', category: 'Phone'},
  {id: 5, name: 'Playstation 5', category: 'Entertainment'}
]

分组逻辑:

const groupedProducts = productList.reduce((result, current) => {
  // 分类不存在时初始化对应空数组
  if (!result[current.category]) {
    result[current.category] = []
  }
  result[current.category].push(current.name)
  return result
}, {})

输出逻辑:

// 按要求格式打印结果
for (const [category, productNames] of Object.entries(groupedProducts)) {
  console.log(category)
  productNames.forEach(name => console.log(`  ${name}`))
}

运行后输出结果完全匹配需求:

Fruit
  Apple
  Melon
Phone
  iPhone
  Samsung Galaxy Note 8
Entertainment
  Playstation 5

如果是页面渲染场景,把console.log替换为DOM拼接逻辑即可,缩进可以用CSS的padding-left或者直接输出空格实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:24:06