gpt4 book ai didi

javascript - 根据多个项目的 JSON 数据创建复杂表

转载 作者:行者123 更新时间:2023-12-01 08:30:04 25 4
gpt4 key购买 nike

我有一个如下所示的 JSON

[{
"teacher": "teacher1",
"student": "student1",
"segment": "product"
},
{
"teacher": "teacher1",
"student": "student1",
"segment": "UNR"
},
{
"teacher": "teacher1",
"student": "student1",
"segment": "product"
},
{
"teacher": "teacher2",
"student": "student1",
"segment": "UNR"
},
{
"teacher": "teacher2",
"student": "student2",
"segment": "product"
}
]

create complex table from the Json data的帮助下我可以创建一个数组来计算每个老师及其计数,我现在想在其中添加另一个详细信息。我想计算每个老师的片段实例,如下所示

[
{
"teacherName": "teacher1",
"teacherCount": "3",
"productCount":"2",
"unrCount":"1"
},
{
"teacherName": "teacher2",
"teacherCount": "2",
"productCount":"1",
"unrCount":"1"
}
]

最佳答案

一种选择是使用reduce 循环遍历数组。使用teacher作为key,将数据汇总成一个对象。使用Object.values将对象转换为数组。

const data = [{"teacher":"teacher1","student":"student1","segment":"product"},{"teacher":"teacher1","student":"student1","segment":"UNR"},{"teacher":"teacher1","student":"student1","segment":"product"},{"teacher":"teacher2","student":"student1","segment":"UNR"},{"teacher":"teacher2","student":"student2","segment":"product"}]

const result = Object.values(data.reduce((c, {teacher,segment}) => {
c[teacher] = c[teacher] || {"teacherName": teacher,"teacherCount": 0,"productCount": 0,"unrCount": 0};
c[teacher].teacherCount++;

if (segment === "product") c[teacher].productCount++;
if (segment === "UNR") c[teacher].unrCount++;

return c;
}, {}));

console.log(result);

关于javascript - 根据多个项目的 JSON 数据创建复杂表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61299800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com