狐的传说
您可以构建一个 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" } ]}