You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于指定JSON数据构建复杂表格并统计教师及细分段实例数

解决方案:统计教师及细分段记录数

我来给你提供一个简洁的JavaScript实现方案,刚好能满足你对教师总记录数、product和UNR细分段的统计需求:

const originalData = [
  { "teacher": "teacher1", "student": "student1", "segment": "product" },
  { "teacher": "teacher1", "student": "student1", "segment": "UNR" },
  { "teacher": "teacher1", "student": "student1", "segment": "product" },
  { "teacher": "teacher2", "student": "student1", "segment": "UNR" },
  { "teacher": "teacher2", "student": "student2", "segment": "product" }
];

const result = Object.values(originalData.reduce((acc, item) => {
  // 检查当前教师是否已在统计对象中,不存在则初始化
  if (!acc[item.teacher]) {
    acc[item.teacher] = {
      teacherName: item.teacher,
      teacherCount: "0",
      productCount: "0",
      unrCount: "0"
    };
  }
  
  // 总记录数+1
  acc[item.teacher].teacherCount = (parseInt(acc[item.teacher].teacherCount) + 1).toString();
  
  // 根据segment更新对应细分段计数
  if (item.segment === "product") {
    acc[item.teacher].productCount = (parseInt(acc[item.teacher].productCount) + 1).toString();
  } else if (item.segment === "UNR") {
    acc[item.teacher].unrCount = (parseInt(acc[item.teacher].unrCount) + 1).toString();
  }
  
  return acc;
}, {}));

console.log(result);

代码逻辑说明:

  • 用reduce方法遍历原始数据,以教师名为键构建统计对象,避免重复统计同一教师
  • 初始化每个教师的统计条目时,把计数都设为字符串类型(和你期望的输出格式完全匹配)
  • 每遍历一条数据,先增加该教师的总记录数,再根据segment的值对应更新productCount或unrCount
  • 最后用Object.values()把统计对象转成你需要的数组格式

运行这段代码后,输出结果完全符合你给出的期望格式:

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

内容的提问来源于stack exchange,提问作者creativated

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 12:37:28