如何再次合并已破坏的对象键?

How can I merge the destructed object keys again?

如您所见,我必须销毁 getters,我需要对它们求和并计算出它们有多少收入。

这是一个示例代码,它是 Vuex 商店中的 getter,但这并不重要,它与 javascript 而不是 vue 本身有关。

    sumIncomes: (
      {
        incomeMonthlyNet,
        incomePension,
        incomeChildBenefit,
        incomeChildSupports,
        incomeSpousalMaintenance,
        incomeParentalBenefit,
        incomeSecondaryWork,
        incomeSelfEmployedWork,
        incomeMiniJob,
        incomeSupplementaryPension,
        incomeRental,
      }
    ) => {
      return (
        incomeMonthlyNet +
        incomePension +
        incomeChildBenefit +
        incomeChildSupports +
        incomeSpousalMaintenance +
        incomeParentalBenefit +
        incomeSecondaryWork +
        incomeSelfEmployedWork +
        incomeMiniJob +
        incomeSupplementaryPension +
        incomeRental
      )
    },

这看起来一点也不优雅,但我突然找不到更好的方法(如果我可以将被破坏的对象存储在一个变量中,那么我可以玩 Object.values 和只是减少它,但我不知道这样)

感谢您的帮助 ;)

是的,你可以,这里有优雅的声明方式

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)
    },

这里有 3 个 return 语句,显然除非您评论第一个,否则永远不会到达第二个和第三个。您可以通过评论第三个来尝试第二个,通过评论第一和第二个来尝试第三个。