将表格 json 数据转换为包装图表的 d3 分层数据

Convert tabular json data to d3 hierarchal data for pack chart

我在 JSON 文件中有一个小数据集,我想将其转换为分层数据格式以创建圆形包装图。 这是我的数据集:

{
"Marks": [
{"student": "Maria", "AI": 95, "DB": 77, "CG": 31, "ITP": 97, "LIT": 45},
{"student": "Sam", "AI": 85, "DB": 37, "CG": 39, "ITP": 45, "LIT": 55}
]
}

这是我正在寻找的输出:

{
"name": "Marks",
 "children": [
  { "name": "Maria",
 "children": [
  { "name": "AI" , "marks" : 95},
  { "name": "DB" , "marks" : 77},
  { "name": "CG" , "marks" : 35},
  { "name": "ITP" , "marks" : 97},
  { "name": "LIT" , "marks" : 45},
]
},
{ "name": "Sam",
 "children": [
  { "name": "AI" , "marks" : 85},
  { "name": "DB" , "marks" : 37},
  { "name": "CG" , "marks" : 39},
  { "name": "ITP" , "marks" : 45},
  { "name": "LIT" , "marks" : 55},
]
}
]
}


知道我该如何处理吗?

试试这个

var newObj = {};
Object.keys(marks).forEach((key) => {
 newObj.name = key;
  newObj.children = [];
  var i = 0;
  marks[key].forEach((element) => {
    Object.keys(element).forEach((k) => {
      if (k == "student") newObj.children.push({ name: element[k], children: [] });
     else newObj.children[i].children.push({ name: k, marks: element[k] });
    });
    i++;
  });
});

结果

{
    "name": "Marks",
    "children": [
        {
            "name": "Maria",
            "children": [
                {
                    "name": "AI",
                    "marks": 95
                },
                {
                    "name": "DB",
                    "marks": 77
                },
                {
                    "name": "CG",
                    "marks": 31
                },
                {
                    "name": "ITP",
                    "marks": 97
                },
                {
                    "name": "LIT",
                    "marks": 45
                }
            ]
        },
        {
            "name": "Sam",
            "children": [
                {
                    "name": "AI",
                    "marks": 85
                },
                {
                    "name": "DB",
                    "marks": 37
                },
                {
                    "name": "CG",
                    "marks": 39
                },
                {
                    "name": "ITP",
                    "marks": 45
                },
                {
                    "name": "LIT",
                    "marks": 55
                }
            ]
        }
    ]
}