Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...