簡體   English   中英

從 JSON 數據為多個項目創建復雜表

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

我有一個看起來像這樣的 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"
            }
        ]

從 Json 數據創建復雜表的幫助下,我可以創建一個數組來計算每個教師及其計數,我現在想在其中添加另一個細節。 我想為每個老師計算段的實例,如下所示

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

假設 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
},{})

一種選擇是使用reduce循環遍歷數組。 teacher為key,將數據匯總成object。 使用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