我需要一点帮助来解决问题,我想看看是否有人可以帮助我:
我有以下格式的对象:
{
red: [
{time: "00:00:05", value: "7"},
{time: "00:00:10", value: "3"}],
green: [
{time: "00:00:05", value: "3"},
{time: "00:00:10", value: "27"}]
}
我需要做什么:
以“时间”和“值”为参考,获取“绿色”和“红色”内每个对象的百分比份额。
在每个“绿色”和“红色”对象上添加份额值。
外观示例:
{
red: [
{time: "00:00:05", value: "7", share: "70%"},
{time: "00:00:10", value: "3", share: "10%"}],
green: [
{time: "00:00:05", value: "3", share: "30%"},
{time: "00:00:10", value: "27", share: "90%"}]
}
有人能帮我吗?我不能做到这一点。
最佳答案
简短的解决方案:
const o = {
red: [
{time: "00:00:05",value: "7"},
{time: "00:00:10",value: "3"}
],
green: [
{time: "00:00:05",value: "3"},
{time: "00:00:10",value: "27"}
]
};
const colors = Object.keys(o);
// saves the sum of all values, for each time
const total = o[colors[0]]
.map(x => x.time)
.map(time => colors
.map(c => +o[c].find(x => x.time == time).value)
.reduce((a, b) => a + b, 0)
);
// adds the 'share' property
colors.forEach(c => o[c].forEach((x, i) => o[c][i].share = `${Math.floor(100*x.value/total[i])}%`))
console.log(o);
关于javascript - 如何找到包含在单独数组中的两个值的百分比份额?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56874733/