Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
117 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...