如何按分类名称对产品对象数组进行合并分组展示
实现思路
- 先对原始对象数组按
category字段分组,将同分类下的产品名称归集到同一数组中 - 遍历分组后的数据,先输出分类名称,再缩进输出该分类下的所有产品名
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
相关产品推荐
相关产品推荐

