javascript - 根据多个项目的 JSON 数据创建复杂表

标签 javascript jquery

我有一个如下所示的 JSON

[{
                "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"
            }
        ]

create complex table from the Json data的帮助下我可以创建一个数组来计算每个老师及其计数,我现在想在其中添加另一个详细信息。我想计算每个老师的片段实例,如下所示

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

最佳答案

一种选择是使用reduce 循环遍历数组。使用teacher作为key,将数据汇总成一个对象。使用Object.values将对象转换为数组。

const data = [{"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(data.reduce((c, {teacher,segment}) => {
  c[teacher] = c[teacher] || {"teacherName": teacher,"teacherCount": 0,"productCount": 0,"unrCount": 0};
  c[teacher].teacherCount++;

  if (segment === "product") c[teacher].productCount++;
  if (segment === "UNR") c[teacher].unrCount++;

  return c;
}, {}));

console.log(result);

关于javascript - 根据多个项目的 JSON 数据创建复杂表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61299800/

相关文章:

jquery - 移动进度条

jquery - 如何在不通过 jQuery 提交的情况下强制进行 html5 表单验证

javascript - 用我的字符串检索天数

javascript - Firebase 函数 - 在 onWrite() 触发器中找不到父属性

javascript - 为什么我的 index.html 页面加载很慢

javascript - 使用 JQuery 使元素褪色意识到单击的元素

php - Ajax 在 php 语句中不起作用

javascript - 找到目标的目标,即强制定向图中 friend 的 friend

javascript - 如何使用 HTML/CSS/JScrollPane 制作漂亮的滚动条

javascript - 在 bootstrap datepicker 中设置 mindate