使用.reduce()对数据结果进行分组

时间:2019-03-21 16:48:17

标签: javascript typescript vue.js

这个问题是该帖子的后续内容: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

在我的查看页面中,我有:

水果-苹果
乳制品-酸奶
水果-香蕉
谷物-百吉饼
谷物-面包
水果-草莓
乳制品-牛奶
谷物-松饼
乳制品-奶酪

我希望我的观点是:

水果-苹果,香蕉,草莓
谷物-百吉饼,面包,松饼
乳制品-酸奶,牛奶,奶酪

0 个答案:

没有答案