[Vuejs]-VUE: calculate 2d array with multple input

0👍

A computed property can only have a single value, you can’t calculate it ‘per row’.

What you can do is have the value be an array, with one entry per row.

The data structure you’re working with is a bit of a pain as the arrays are transposed relative to the table. Still, it can be done with a bit of fighting.

First, in the template you’d add a suitable <td> to the end of the rows:

<tr v-for="(classlist, index) in classlists" :key="'lab' + classlist.id">
  ... other tds not shown ...
  <td>
    {{ studentTotalScores[index] }}
  </td>
</tr>

Then studentTotalScores would be:

studentTotalScores: function() {
  return this.classlists.map((c, index) => {
    return this.labs.reduce((acc, item) => {
      const value = parseInt(item.value[index], 10) || 0
      return acc + value
    }, 0)
  })
}

I’ve added a base of 10 to parseInt to ensure consistent parsing, as well as || 0 so that NaN will be treated as 0.

Leave a comment