实际上我的函数计算每个对象中所有相同键的总和
const arr = [{id:1, "my color":1,"my fruit":4},{id:2,"my color":2,"my fruit":4}];
const res = arr.reduce((a, { id, ...rest }) => {
Object.entries(rest).forEach(([key, val]) => {
a[key] = (a[key] || 0) + val;
});
return a;
}, {});
result is >> [{"my color":3,"my fruit":8}
我想得到他们的百分比(值/值的总和)而不是他们的总和,就像这样
{ "my color": 27, "my fruit": 73 }
答案 0 :(得分:0)
首先总结所有值,然后将每个条目除以:
// Sum up all properties with same key
const sum = { };
for(const entry of array) {
for(const [key, value] of Object.entries(entry)) {
sum[key] = (sum[key] || 0) + value;
}
}
// Map the array to an array of percentages
const percentage = array.map(entry => {
const result = {};
for(const [key, value] of Object.entries(entry)) {
result[key] = value / sum[key] * 100;
}
return result;
});
答案 1 :(得分:0)
尝试以下
var obj = {"my color":3,"my fruit":8};
var total = Object.values(obj).reduce((a,c) => a+c, 0);
Object.keys(obj).forEach(k => obj[k] = Math.round(obj[k]*100/total));
console.log(obj);