JavaScript如何按categoryId属性对对象数组进行分组展示
实现方案
你可以通过数组的reduce方法做分组归类,再按分类ID排序输出即可,JavaScript示例代码如下:
const rawData = { "events": [ { "id": 0, "description": "Monthly play with friends", "categoryId": 0 }, { "id": 1, "description": "Buy Goods", "categoryId": 2 }, { "id": 2, "description": "Yoga", "categoryId": 1 }, { "id": 3, "description": "Lunch", "categoryId": 0 }, { "id": 4, "description": "Feed wild & free Bearded Dragons", "categoryId": 3 }, { "id": 5, "description": "Come to help our little friends", "categoryId": 3 }, { "id": 6, "description": "Come and share your expertise", "categoryId": 3 }, { "id": 7, "description": "Dinner with Brother", "categoryId": 2 } ] } // 按categoryId分组 const groupedResult = rawData.events.reduce((groupMap, event) => { const categoryId = event.categoryId // 分类不存在则初始化空数组 if (!groupMap[categoryId]) { groupMap[categoryId] = [] } groupMap[categoryId].push(event.description) return groupMap }, {}) // 按分类ID升序输出 Object.keys(groupedResult) .sort((a, b) => Number(a) - Number(b)) .forEach(categoryId => { console.log(`CategoryId ${categoryId}`) groupedResult[categoryId].forEach(desc => console.log(desc)) // 不同分类之间输出空行分隔 console.log() })
分组展示效果
CategoryId 0
- 和朋友每月聚会玩耍
- 午餐
CategoryId 1
- 瑜伽
CategoryId 2
- 采购商品
- 和兄弟共进晚餐
CategoryId 3
- 投喂野生自由活动的鬃狮蜥
- 来帮助我们的小伙伴
- 来分享你的专业经验
内容的提问来源于stack exchange,提问作者Carlos Spagnoletti
相关产品推荐
相关产品推荐

