扁平化某些嵌套数据时出现问题



我有一些如下所示的数据,我想得到类型student的所有正、负和中性的和,所以我做了一个d3.nest方法,在该方法中,我使用键作为student,并返回了提到的值的和。

{Type: student, positive: 2, negative: 1, neutral:0}, {Type: student, positive: 1, negative: 1, neutral:0}, {Type: student, positive: 1, negative: 1, neutral:0}, {Type: student, positive: 1, negative: 2, neutral:0} 

这是d3.nest的结果,在.rollup返回语句中,我指定了类似positive: d3.sum(d,function(f){ return f.positive;})等的值名称。下面是结果。

`key: "student"
value: {positive: 5, negative: 5, neutral: 0}`

然而,要绘制雷达图,我需要将数据压平,使其达到下面的水平,但我不知道如何做到这一点。我试着按照下面的代码进行操作,但一直出现错误,请你帮忙。

{student: student, positive:5, negative:5, neutral:0}

我已经尝试了每个循环,它没有工作

var flatData = []
subStudent.forEach(function(sub){
sub.value(function(subval){
flatData.push({
level: sub.key,
value: subval.value
});
});
});
console.log(JSON.stringify(flatData))

可能真的不需要d3.nest(),除非你有理由?

你可以用reduce来做(但我也会包括下面的d3.nest()示例(:

const input = [
{Type: 'student', positive: 2, negative: 1, neutral:0},
{Type: 'student', positive: 1, negative: 1, neutral:0},
{Type: 'student', positive: 1, negative: 1, neutral:0},
{Type: 'student', positive: 1, negative: 2, neutral:0},
{Type: 'other', positive: 2, negative: 0, neutral:1},
{Type: 'other', positive: 1, negative: 1, neutral:0},
{Type: 'other', positive: 1, negative: 1, neutral:0}
];
const output = Object.values(input.reduce((aggObj, item) => {

if (!aggObj.hasOwnProperty(item.Type)) aggObj[item.Type] = item;
else {
for (let key in item){
if (key != "Type") aggObj[item.Type][key] += item[key];
} 
}
return aggObj
}, {}))
console.log(output)

输入:

[
{ Type: 'student', positive: 2, negative: 1, neutral:0 },
{ Type: 'student', positive: 1, negative: 1, neutral:0 },
{ Type: 'student', positive: 1, negative: 1, neutral:0 },
{ Type: 'student', positive: 1, negative: 2, neutral:0 },
{ Type: 'other',   positive: 2, negative: 0, neutral:1 },
{ Type: 'other',   positive: 1, negative: 1, neutral:0 },
{ Type: 'other',   positive: 1, negative: 1, neutral:0 }
]

输出:

[
{ Type: "student", positive: 5, negative: 5, neutral: 0 },
{ Type: "other",   positive: 4, negative: 2, neutral: 1 }
]

如果您需要/想要d3.nest(),您可以这样做(相同的输入和输出(:

const input = [
{Type: 'student', positive: 2, negative: 1, neutral:0},
{Type: 'student', positive: 1, negative: 1, neutral:0},
{Type: 'student', positive: 1, negative: 1, neutral:0},
{Type: 'student', positive: 1, negative: 2, neutral:0},
{Type: 'other', positive: 2, negative: 0, neutral:1},
{Type: 'other', positive: 1, negative: 1, neutral:0},
{Type: 'other', positive: 1, negative: 1, neutral:0}
];
const nested = d3.nest()
.key(d => d.Type)
.rollup(d => ({
positive: d3.sum(d, f => f.positive),
negative: d3.sum(d, f => f.negative),
neutral: d3.sum(d, f => f.neutral),
}))  
.entries(input)

const output = nested.map(item => {
//console.log(item)
return {Type: item.key, ...item.value}
})
console.log(output)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

最新更新