Home > Mobile >  Reading all objects from multidimensional array
Reading all objects from multidimensional array

Time:10-13

I want to read all objects from multidimensional array which looks like this:

const useMap = ref([
  // ====================== ROW 1 ======================
  [
    {
      x: 1,
      y: 1,
      currentPosition: false,
      color: "white",
      isWinning: false,
    },
    {
      x: 16,
      y: 1,
      currentPosition: false,
      color: "white",
      isWinning: false,
    },
  ],
  // ====================== ROW 2 ======================
  [
    {
      x: 1,
      y: 2,
      currentPosition: false,
      color: "white",
      isWinning: false,
    },
    {
      x: 16,
      y: 2,
      currentPosition: false,
      color: "white",
      isWinning: false,
    },

...

Already Im reading values by single rows like this:

      <div v-for="tile in map[0]" :key:="tile" :tile="tile">
        <div >{{ tile.y }} | {{ tile.x }}</div>
      </div>
      <div v-for="tile in map[1]" :key:="tile" :tile="tile">
        <div >{{ tile.y }} | {{ tile.x }}</div>
      </div>

...

Is there any option to read all rows once and not by single rows?

CodePudding user response:

Nested arrays can be flattened with flat, and a computed is used to transform data to required shape before it's used:

const tiles = computed(() => useMap.value.flat());

Then it's used like intended:

  <div v-for="tile in tiles" :key:="tile" :tile="tile">

CodePudding user response:

You can achieve this requirement by converting the multi dimensional array into a single dimensional array using Array.flat() method and then iterate the values using v-for in the template.

Live Demo :

const { ref, reactive, readonly, computed } = Vue;

const App = {
  setup () {
    const useMap = ref([
      [
        {
          x: 1,
          y: 1,
          currentPosition: false,
          color: "white",
          isWinning: false,
        },
        {
          x: 16,
          y: 1,
          currentPosition: false,
          color: "white",
          isWinning: false,
        }
      ],
      [
        {
          x: 1,
          y: 2,
          currentPosition: false,
          color: "white",
          isWinning: false,
        },
        {
          x: 16,
          y: 2,
          currentPosition: false,
          color: "white",
          isWinning: false,
        }
      ]
    ])

    const tiles = computed(() => useMap.value.flat());

    return { tiles }
  }
}

Vue.createApp(App).mount("#app");
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
  <div v-for="tile in tiles" :key:="tile" :tile="tile">
    <div >{{ tile.y }} | {{ tile.x }}</div>
  </div>
</div>

  • Related