我有一个包含num和sum
的对象数组<div class="container">
<div class="jumbotron" style="width:100%">
<h1>
ConfigTool Web Interface
</h1>
<p>
Edit the config variables here and click save.
</p>
</div>
<div class="form-group row">
<label class="col-2">Name:</label>
<input class="form-control col-10" type="text" />
</div>
</div>
我想要的是:
[
{num: 1, sum: 10},
{num: 1, sum: 2},
{num: 1, sum: 3},
{num: 2, sum: 1},
{num: 2, sum: 40},
{num: 2, sum: 100},
{num: 3, sum: 0},
{num: 4, sum: 0},
]
非常感谢任何帮助
答案 0 :(得分:1)
一个选项是reduce
进入由num
s索引的对象,然后将map
该对象转换为数组:
const input=[{num:1,sum:10},{num:1,sum:2},{num:1,sum:3},{num:2,sum:1},{num:2,sum:40},{num:2,sum:100},{num:3,sum:0},{num:4,sum:0},]
const outputObj = input.reduce((a, { num, sum }) => {
if (!a[num]) a[num] = { count: 0, totalSum: 0 };
a[num].count++;
a[num].totalSum += sum;
return a;
}, {});
const output = Object.entries(outputObj)
.map(([key, val]) => ({ [key] : val }));
console.log(output);
&#13;
答案 1 :(得分:0)
您可以使用reduce
方法对数组进行分组,然后使用其他reduce
方法,以便为每个键找到count
和totalSum
属性。
let arr = [ {num: 1, sum: 10}, {num: 1, sum: 2}, {num: 1, sum: 3}, {num: 2, sum: 1}, {num: 2, sum: 40}, {num: 2, sum: 100}, {num: 3, sum: 0}, {num: 4, sum: 0}, ]
var groupBy = function(arr, key) {
return arr.reduce(function(acc, x) {
(acc[x[key]] = acc[x[key]] || []).push(x);
return acc;
}, {});
};
let grouped = groupBy(arr, 'num');
let result = Object.keys(grouped).reduce(function(acc, key){
let obj ={ [key] : {count : grouped[key].length, totalSum: grouped[key].map(a => a.sum).reduce((a,b) => a + b)}}
acc.push(obj)
return acc;
},[]);
console.log(result);