简体   繁体   中英

How can I merge the destructed object keys again?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM