从 Json 数据创建复杂表

我有一个看起来像这样的 JSON


[

{

    "teacher": "teacher1",

    "student": "student1"

    },

{

   "teacher": "teacher1",

    "student": "student1"

    },

{

    "teacher": "teacher1",

    "student": "student1"

    },

{

    "teacher": "teacher2",

    "student": "student1"

    },

{

   "teacher": "teacher2",

    "student": "student2"

    }

]

我想将它转换成这样的方式,它可以向我显示每个老师的计数


[

    {

        "teacherName": "teacher1",

        "teacherCount": "3"

    },

    {

        "teacherName": "teacher2",

        "teacherCount": "2"

    },

]

我正在开发一个节点项目,我需要在表格中打印这些数据。


四季花海
浏览 212回答 2
2回答

狐的传说

您可以构建一个 Map(使用.reduce()),它由teacher值索引/键控。存储在teacher 中的值是在您的对象数组中看到teacher 的次数的计数。Array.from()然后,您可以使用Mapbuild using reduce 从映射中获取每个键值对(其中键是teacherName,值是teacherCount)。要获取每个键值对,您可以使用 Array.from() 的映射函数并将每个键值 ([key, value]) 映射到一个对象,如下所示: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);

青春有我

您可以使用 将您的计数收集到一个唯一的集合中reduce,如果存在,则增加教师,否则将其初始化为 1。然后是如何格式化的示例如下使用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"    }  ]}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript