[Vuejs]-Iterate through grouped collection

0👍

First, leave comment if your real data have structure like this, then I edit this answer:

let user = [
  {
    id: 8,
    products: {
      3: [
        {id: 4, value: 25},
        {id: 5, value: 20}
      ],
      4: [
        {id: 6, value: 14},
        {id: 7, value: 30},
        {id: 8, value: 20}
      ]
    }
  }
]

function sum (arr) {
  Object
    .entries(arr[0].products)
    .forEach(pair => {
      let sum = Array
        .from(pair[1].map(o => o.value))
        .reduce((a, b) => a + b)
      console.log(`Sum for product ${pair[0]} is ${sum}`)
    })
}

sum(user)

Or in Vue component:

export default {
  data () {
    return {
      user: []
    }
  },

  computed: {
    watchedOnly () {
      let result = {}

      Object
        .entries(this.user[0].products)
        .forEach(pair => {
          let sum = Array
            .from(pair[1].map(o => o.value))
            .reduce((a, b) => a + b)
          result[pair[0]] = sum
        })

      return result
    }
  }
}

Use it in template:

<p v-for="(sum, product) in watchedOnly">
  Sum for product {{ product }} is {{ sum }}
</p>

Leave a comment