繁体   English   中英

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

[英]How can I merge the destructed object keys again?

如您所见,我必须销毁吸气剂,将它们求和并获得多少收入。

这是一个示例代码,它是Vuex商店中的吸气剂,但这并不重要,它与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语句,很明显,除非您注释第一个,否则永远不会到达第二个和第三个。 您可以通过注释第三个来尝试第二个,而通过注释第一个和第二个来尝试第三个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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