首页 > 解决方案 > 使用 .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

在我的视图页面中,我有:

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

我希望我的观点是:

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

标签: javascripttypescriptvue.js

解决方案


推荐阅读