I have a JSON that looks like this
[{
"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. 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.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. Use teacher
as the key to summarize the data into an object. Use Object.values
to convert object into an array.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.