gpt4 book ai didi

javascript - 计算对象的百分比

转载 作者:行者123 更新时间:2023-11-29 23:20:29 25 4
gpt4 key购买 nike

我的函数映射一个对象来创建新闻键。我的新键“百分比”计算键“数据”的每个值的百分比。百分比 = 所有值的值/总和。我不知道为什么它不起作用?

 

var myObject = {
id1: {
"value 1": 3,
"value 2": 2
},
id2: {
"value 1": 2,
"value 2": 2
},
id3: {
"value 1": 4,
"value 2": 3
}
};

var series = _(myObject).map(function(g, key) {

var total = 0;
for (var i in Object.values(g)) {
total += Object.values(g)[i];
}

return {
type: 'column',
name: key,
total: total,
data: Object.values(g),
percent:Object.values(g)/total
};
});
console.log(series)

预期的结果

[{
"type": "column",
"name": "id1",
"total": 5,
"data": [ 3, 2 ],
"percent": [ 0.6, 0.4 ],
}, {
"type": "column",
"name": "id2",
"total": 4,
"data": [ 2, 2 ],
"percent": [ 0.5, 0.5 ],
}, {
"type": "column",
"name": "id3",
"total": 7,
"data": [ 4, 3 ],
"percent": [ 0.57, 0.43 ],
}]

最佳答案

您可以通过获取键/值对来映射新对象,首先获取值的总和,然后计算所需的百分比(不是基于 100,而是 1)。

var object = { id1: { "value 1": 3, "value 2": 2 }, id2: { "value 1": 2, "value 2": 2 }, id3: { "value 1": 4, "value 2": 3 } },
result = Object.entries(object).map(([name, values]) => {
var data = Object.values(values),
total = data.reduce((a, b) => a + b, 0),
percent = data.map(p => p / total);

return { type: 'column', name, total, data, percent };
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

适用于 ES5 语法的 IE。

var object = { id1: { "value 1": 3, "value 2": 2 }, id2: { "value 1": 2, "value 2": 2 }, id3: { "value 1": 4, "value 2": 3 } },
result = Object.keys(object).map(function(name) {
var data = Object.keys(object[name]).map(function (k) { return object[name][k]; }),
total = data.reduce(function (a, b) { return a + b; }, 0),
percent = data.map(function (p) { return p / total; });

return { type: 'column', name: name, total: total, data: data, percent: percent };
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 计算对象的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50875268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com