I am trying to sum the object values based on selected keys which are available in every object of the array. My problem is how to handle the percentage rate. In the sample of code below, the satisfaction_rate should have 48.
My output should be:
{
'students' : 87,
'books': 32,
'satisfaction_rate': 48
}
const myData = [
{
'students' : 30,
'books': 10,
'satisfaction_rate': "60%",
'returning_students': 14
}, {
'students' : 25,
'books': 8,
'satisfaction_rate': "45%",
'returning_students': 14
}, {
'students' : 32,
'books': 14,
'satisfaction_rate': "39%",
'returning_students': 19
}
];
const keysToConsider = ['students', 'books', 'satisfaction_rate'];
function getSumOrAvgValuesOfKeys(data){
const obj = {};
let val = 0;
keysToConsider.forEach(el => {
data.forEach(element => {
if (typeof(element[el] === 'string')) {
val += parseInt(element[el], 10);
} else {
val += element[el];
}
});
obj[el] = val;
// Reset value
val = 0;
});
return obj;
}
console.log(getSumOrAvgValuesOfKeys(myData));
satisfaction_ratecalculated for each item?