我从我的API接收数据,如下所示:
[
{grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"},
{grade: "Grade B", id: 2, ifsGrade: "B1XX", ifsType: "02XX", points: 15, type: "Type_1"},
{grade: "Grade C", id: 3, ifsGrade: "C1XX", ifsType: "03XX", points: 1, type: "Type_1"},
{grade: "Grade A", id: 4, ifsGrade: "A2XX", ifsType: "04XX", points: 23, type: "Type_2"},
{grade: "Grade B", id: 5, ifsGrade: "B2XX", ifsType: "05XX", points: 26, type: "Type_2"}
]
字符串
感谢StackOverflow的帖子,我成功地将我的列表转换为按类型对每个项目进行分组,如下所示:
var API_DATA = [
{grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"},
{grade: "Grade B", id: 2, ifsGrade: "B1XX", ifsType: "02XX", points: 15, type: "Type_1"},
{grade: "Grade C", id: 3, ifsGrade: "C1XX", ifsType: "03XX", points: 1, type: "Type_1"},
{grade: "Grade A", id: 4, ifsGrade: "A2XX", ifsType: "04XX", points: 23, type: "Type_2"},
{grade: "Grade B", id: 5, ifsGrade: "B2XX", ifsType: "05XX", points: 26, type: "Type_2"}
];
Array.prototype.groupBy = function(k) {
return this.reduce((acc, item) => ((acc[item[k]] = [...(acc[item[k]] || []), item]), acc),{});
};
TABLE_DATA = API_DATA.groupBy("type")
console.log(TABLE_DATA)
型
不幸的是,我不能在Angular 材质mat-table
的dataSource中使用这个结果,因为它不是一个列表:
Error: Provided data source did not match an array, Observable, or DataSource
型
如何检索由多个列表组成的列表:
[
[
{grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"},
{grade: "Grade B", id: 2, ifsGrade: "B1XX", ifsType: "02XX", points: 15, type: "Type_1"},
{grade: "Grade C", id: 3, ifsGrade: "C1XX", ifsType: "03XX", points: 1, type: "Type_1"}
],
[
{grade: "Grade A", id: 4, ifsGrade: "A2XX", ifsType: "04XX", points: 23, type: "Type_2"},
{grade: "Grade B", id: 5, ifsGrade: "B2XX", ifsType: "05XX", points: 26, type: "Type_2"}
]
]
型
谢谢你的帮助。
4条答案
按热度按时间mpbci0fu1#
你可以从对象中得到值。
个字符
2023年更新
新标准
Object.groupBy
:的字符串
igsr9ssn2#
您可以通过两种方式对这些数据进行分组。
object
array
Demo
注意:我使用
JSON.stringify(group, null, 2)
.来美化输出。字符串
a1o7rhls3#
字符串
neskvpey4#
可以在lodash上使用_.groupBy()函数
个字符