as you can see I have to destruct the getters which I need to sum them and get how much income they have.
here is an example code this is a getter in Vuex store, but this is not important it's rather related to javascript and not vue itself.
sumIncomes: (
{
incomeMonthlyNet,
incomePension,
incomeChildBenefit,
incomeChildSupports,
incomeSpousalMaintenance,
incomeParentalBenefit,
incomeSecondaryWork,
incomeSelfEmployedWork,
incomeMiniJob,
incomeSupplementaryPension,
incomeRental,
}
) => {
return (
incomeMonthlyNet +
incomePension +
incomeChildBenefit +
incomeChildSupports +
incomeSpousalMaintenance +
incomeParentalBenefit +
incomeSecondaryWork +
incomeSelfEmployedWork +
incomeMiniJob +
incomeSupplementaryPension +
incomeRental
)
},
this don't seem elegant at all, but I suddenly couldn't find a better way for this (if I could store for example the destructed object in a variable then I could play with Object.values and just reduce it but I don't know of such)
Thanks for your help ;)
Yes you can, here are there elegant declarative ways of doing it
sumIncomes: (
incomeObject
) => {
// If your object only contain income Properties you can do this
return Object.values(incomeObject).reduce((acc, cur) => acc + cur,0)
// If your object contain other keys and you know that income Properties all
// have number values you can do this
return Object.keys(incomeObject).reduce((acc, key) => key.startsWith('income') ? acc + incomeObject[key] : acc ,0)
// if none of the above works because in your object you have a prop called for example incomeTest and
// its value is a string then you can do this
const arrOfPropsToSum = ['incomeMonthlyNet',
'incomePension',
'incomeChildBenefit',
'incomeChildSupports',
'incomeSpousalMaintenance',
'incomeParentalBenefit',
'incomeSecondaryWork',
'incomeSelfEmployedWork',
'incomeMiniJob',
'incomeSupplementaryPension',
'incomeRental']
return arrOfPropsToSum.reduce((acc, propKey) => acc + incomeObject[propKey], 0)
},
There are here 3 return statements, obviously unless you comment the first one, the second and third are never gonna be reached. You can try the second by commenting the third, and the third by commenting the first and the second.