简体   繁体   中英

create complex table from the Json data

I have a JSON that looks like this

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

I want to convert it in a way that it shows me the count for each teacher like this

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

I am working on a node project where I need to print this data in a table.

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

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" } ] }

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.

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