Возможно, на самом деле не нужен 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>