[Vuejs]-Vuejs setting an array

3👍

Vue can iterate Objects the same as they do Arrays, if you insist on named values why not do this:

cells: {
  0: {},
  1: {},
  2: {}
}

If you got unwanted “data” in your array, you could say the following.

const filteredCells = row.cells.filter(cell => cell !== undefined)

and then iterate the filteredCells instead, id make filteredCells a computed value.

v-for="cell in filteredCells"

Keep index:

export default {
  data() {
    return {
      row: {
        cells: [
          {name: 'peter'}, 
          {name: 'louise'}, 
          {name: 'hans'}, 
          undefined, 
          {name: 'mia'}, 
          {name: 'john'}
        ]
      }
    }
  },

  computed: {
    filteredCellsWithIndex() {
      if (!this.row || !this.row.cells) {
        return
      }

      const { cells } = this.row

      return cells.map((cell, index) => {
        if (cell === undefined) {
          return
        }

        cell.yourIndex = index
        return cell
       }).filter(cell => cell !== undefined)
    }
  }
}
👤Abarth

0👍

There are a couple of ways to cleanly remove your undefined values without making your template overly complicated.

Create a filter.

v-for="cell in row.cells | isDefined"
{
  filters: {
    isDefined(items) {
      return items.filter(it => it !== undefined)
    }
  }
}

Or use a computed property.

v-for="cell in cells"
{
  computed: {
    cells() {
      return this.row.cells.filter(it => it !== undefined)
    }
  }
}

Leave a comment