简体   繁体   English

从 JSON 数据为多个项目创建复杂表

[英]create complex table from the JSON data for multiple items

I have a JSON that looks like this我有一个看起来像这样的 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"
            }
        ]

With the help of create complex table from the Json data i can create an array counting each teacher and its count by I want to add another detail in it now.从 Json 数据创建复杂表的帮助下,我可以创建一个数组来计算每个教师及其计数,我现在想在其中添加另一个细节。 I want to calculate the instance of the segment for each teacher as well like below我想为每个老师计算段的实例,如下所示

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

let say d is your json, then this code will work.假设 d 是您的 json,那么此代码将起作用。

d.reduce((s, i)=>{
    teacher=i["teacher"]
    t=(s[teacher]==null)?{teacherCount:0}:s[teacher]
    seg=i['segment']
    t[seg]=(t[seg]==null)?1:(t[seg]+1)
    t["teacherCount"]+=1
    s[teacher]=t
    return s
},{})

One option is using reduce to loop thru the array.一种选择是使用reduce循环遍历数组。 Use teacher as the key to summarize the data into an object.teacher为key,将数据汇总成object。 Use Object.values to convert object into an array.使用Object.values将 object 转换为数组。

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM