簡體   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