I have an object, where i want to calculate the percentage and display in the maps, currently the data i am getting is a raw data in an object.
Here is the object that i am receiving from backend
JavaScript
x
9
1
[{
2
"date": "26/08/2021",
3
"walking": 965.2107,
4
"running": 964.0539,
5
"sleeping": 962.1473,
6
"swimming": 961.8081,
7
"studying": 961.5081,
8
}]
9
Based on the object i want the percentage to be calculated and replaced in the respective key/value pair. It will take the object value, sum it up and calculate the percentage. This is what i am expecting to return
JavaScript
1
9
1
[{
2
"date": "26/08/2021",
3
"walking": 20,
4
"running": 20,
5
"sleeping": 20,
6
"swimming": 20,
7
"studying": 20,
8
}]
9
Advertisement
Answer
JavaScript
1
18
18
1
const data = [{
2
"date": "26/08/2021",
3
"walking": 965.2107,
4
"running": 964.0539,
5
"sleeping": 962.1473,
6
"swimming": 961.8081,
7
"studying": 961.5081,
8
}];
9
10
const dataInPerCents = data.map(item => {
11
const itemCopy = {item};
12
const keys = Object.keys(itemCopy).filter(key => key !== "date");
13
const sum = keys.reduce((sum, key) => sum + itemCopy[key], 0);
14
keys.forEach(key => itemCopy[key] = Math.round(100 * itemCopy[key] / sum));
15
itemCopy.top3 = keys.sort((key1, key2) => item[key2] - item[key1]).slice(0, 3); // Asked in comment below
16
return itemCopy;
17
});
18
console.log(dataInPerCents);