javascript - 使用 .reduce() 对数据结果进行分组
问题描述
这个问题是这篇文章的后续问题:Grouping api results by title
我已经实现了 reduce,但我得到了一个构建错误。
这是我的代码:
productCategories: Model[] = [];
beforeMount(){
this.get(`...`).then(data => {
Array(data).reduce((acc, curr) => {
let key;
for(let x = 0; x<curr.products.length; x++){
key = curr.products[x].type.ediable.categoryName;
this.productCategories.push(
...acc,
[key]:[...(acc[key] || []), curr.products[x].type.title])
}
}, {});
});
}
这是我得到的构建错误[key]:
let key: any
Argument of type 'any[]' is not assignable to parameter of type 'Model'.
Property 'id' is missing in type 'any[]'
我不确定这个错误意味着什么去解决它。
这是我的结果的信息:
获取数据:
beforeMount(){
this.get(`...`).then(data => {this.results = data.results;});
}
数据结构:
Store - object
name
id
products: [Array of objects]
0: Object
id: 1
type: Object
id: 543
title: string
ediable: object
categoryName: string
categoryId: number
1: Object
id: 2
type: Object
id: 544
title: string
ediable: object
categoryName: string
categoryId: number
2: Object
id: 3
type: Object
id: 545
title: string
ediable: object
categoryName: string
categoryId: number
数据示例:
ediable.categoryName = fruit
type.title = apple
ediable.categoryName = dairy
type.title = yogurt
ediable.categoryName = fruit
type.title = banana
ediable.categoryName = grains
type.title = bagels
ediable.categoryName = grains
type.title = bread
ediable.categoryName = fruit
type.title = strawberry
ediable.categoryName = dairy
type.title = milk
ediable.categoryName = grains
type.title = muffins
ediable.categoryName = dairy
type.title = cheese
在我的视图页面中,我有:
水果 - 苹果
奶制品 - 酸奶
水果 - 香蕉
谷物 - 百吉饼
谷物 - 面包
水果 - 草莓
奶制品 - 牛奶
谷物 - 松饼
奶制品 - 奶酪
我希望我的观点是:
水果 - 苹果、香蕉、草莓
粒 - 百吉饼、面包、松饼
奶制品 - 酸奶、牛奶、奶酪
解决方案
推荐阅读
- ffmpeg - 通过 FFMPEG 管道使文件持续时间松散
- hive - 根据 Hive 中的大小进行过滤
- php - 使用 codeigniter 和 ajax 发送电子邮件,电子邮件已发送但出现错误消息
- objective-c - UICollectionViewFlowlayout 行为奇怪
- c++ - What's causing my prime numbers to all vanish? [C++]
- java - 提交 Spring 表单时无法点击控制器
- c# - WPF Webview's IsPrivateNetworkClientServerCapabilityEnabled ignored when using ItemTemplate
- netbeans - JMS ActiveMQ and Netbeans
- c# - 签名证书的指纹
- c# - Unity3d - 在 ios 构建上加载视频播放器的外部 url 时出错