Create Complex Table From The Json Data
I have a JSON that looks like this [ { 'teacher': 'teacher1', 'student': 'student1' }, { 'teacher': 'teacher1', 'student': 'student1' }, { 'teacher': 'te
Solution 1:
You can build a Map (using .reduce()
), which is indexed/keyed by the teacher
value. The value stored at the teacher is the count of the number of times that teacher has been seen in your array of objects. You can then use Array.from()
with the Map
built using reduce to get each key-value pair from the map (where the key is the teacherName and value is the teacherCount). To get each key-value pair, you can use the mapping function of Array.from() and map each key-value ([key, value]) to an object like so:
const data = [{ "teacher": "teacher1", "student": "student1" }, { "teacher": "teacher1", "student": "student1" }, { "teacher": "teacher1", "student": "student1" }, { "teacher": "teacher2", "student": "student1" }, { "teacher": "teacher2", "student": "student2" } ];
const res = Array.from(data.reduce((map, {teacher}) => {
return map.set(teacher, (map.get(teacher) || 0) + 1);
}, new Map), ([teacherName, teacherCount]) => ({teacherName, teacherCount}));
console.log(res);
Solution 2:
You can collect your counts into a unique set using reduce
, incrementing the teacher if it exists, otherwise initiating it to 1. Then an example of how to format follows using map
.
let data = getData();
let teachers = data.reduce((acc, val) => {
if (val.teacher in acc)
acc[val.teacher]++;
else
acc[val.teacher] = 1;
return acc;
}, {});
let formatted = Object.entries(teachers).map(
([teacherName, teacherCount]) => ({ teacherName, teacherCount })
);
console.log(formatted);
/*****************************************************************/
function getData() {
return [{
"teacher": "teacher1",
"student": "student1"
},
{
"teacher": "teacher1",
"student": "student1"
},
{
"teacher": "teacher1",
"student": "student1"
},
{
"teacher": "teacher2",
"student": "student1"
},
{
"teacher": "teacher2",
"student": "student2"
}
]
}
Post a Comment for "Create Complex Table From The Json Data"