【问题标题】:Adding together nested data () object values with identical keys in VueJS Components在VueJS组件中将具有相同键的嵌套数据()对象值相加
【发布时间】:2019-02-17 18:09:42
【问题描述】:

在我的 VueJS 组件的 data() {} 返回中,我有一堆具有相同键的值嵌套在相邻对象中。

示例:

data() { 
  return {
     foo: {
         userScore: 10,
         computerScore: 5
     },
     bar: {
         userScore: 22,
         computerScore: 100
     }
  }
}

添加bar.userScorefoo.userScore 而不必每次都写出完整的JSON 路由的最佳/性能最好的方法是什么? (我为此编写的组件有大约 40+ 的这些分数,所以在计算中进行死记硬背似乎有点奇怪)

有没有办法访问这些相同的属性,例如*.userScore

感谢阅读!

【问题讨论】:

    标签: javascript json vue.js addition


    【解决方案1】:

    你可以reduce得到一个总结:

    const sum = Object.keys(this.$data).reduce((sum, key) => {
      if (this.$data[key].hasOwnProperty('userScore')) {
        return (sum + this.$data[key].userScore)
      }
      return sum
    }, 0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      相关资源
      最近更新 更多