gpt4 book ai didi

javascript - 计算对象属性的百分比

转载 作者:行者123 更新时间:2023-12-04 07:13:22 24 4
gpt4 key购买 nike

我有一个对象,我想在其中计算百分比并在 map 中显示,目前我得到的数据是对象中的原始数据。
这是我从后端收到的对象

          [{
"date": "26/08/2021",
"walking": 965.2107,
"running": 964.0539,
"sleeping": 962.1473,
"swimming": 961.8081,
"studying": 961.5081,
}]
基于对象,我希望在相应的键/值对中计算和替换百分比。它将获取对象值,将其相加并计算百分比。
这是我期待返回的
          [{
"date": "26/08/2021",
"walking": 20,
"running": 20,
"sleeping": 20,
"swimming": 20,
"studying": 20,
}]

最佳答案

const data = [{
"date": "26/08/2021",
"walking": 965.2107,
"running": 964.0539,
"sleeping": 962.1473,
"swimming": 961.8081,
"studying": 961.5081,
}];

const dataInPerCents = data.map(item => {
const itemCopy = {...item};
const keys = Object.keys(itemCopy).filter(key => key !== "date");
const sum = keys.reduce((sum, key) => sum + itemCopy[key], 0);
keys.forEach(key => itemCopy[key] = Math.round(100 * itemCopy[key] / sum));
itemCopy.top3 = keys.sort((key1, key2) => item[key2] - item[key1]).slice(0, 3); // Asked in comment below
return itemCopy;
});
console.log(dataInPerCents);

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

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