Cats萌萌
可能不需要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>