My function is supposed to map an object to create new keys. The new key "percent" is meant to calculate the percentage of each value of the key "data". It should be calculated as the value divided by the sum of all values. However, for some reason, it's not working correctly.
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)
The expected result should look like this:
[{
"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 ],
}]