securenova
securenova

Reputation: 502

How to make iterations using v-for directive on nested array (array in array)

I am new to Vue and I came upon a situation that I would like to have some advice on.

In my js file I have some arrays that contain some data that I would like to insert in a table:

const d1=[{col1:"aaa1",col2:"bbb1",col3:"ccc1",col4:"ddd1",col5:"eee1"},
          {col1:"aaa2",col2:"bbb2",col3:"ccc2",col4:"ddd2",col5:"eee2"}]
const d2=[{col1:"fff1",col2:"ggg1",col3:"hhh1",col4:"iii1",col5:"jjj1"},
          {col1:"aaa2",col2:"bbb2",col3:"ccc2",col4:"ddd2",col5:"eee2"}]

then I saved the two arrays in another variable called availableData

const availableData=[d1,d2];

my vue instance as follows:

new Vue({
  el: '#c1',
  data: {
    availableData,
  }
});

In my HTML I am trying to add a for loop(v-for) in my row div so the row can display each of data in my availableData variable, but I am having some problems trying to pass d1 to the first row and d2 to the second,

<div id="c1" class="columns">

// ...some code

    <div class="row" v-for="data in availableData">
        <div class="cell">
            {{data.col1}}
        </div>
        <div class="cell">
            {{data.col2}}
        </div>
        <div class="cell">
            {{data.col3}}
        </div>
        <div class="cell">
            {{data.col4}}
        </div>
        <div class="cell">
            {{data.col5}}
        </div>
    </div>
</div>

Of course, the v-for statement is not correct since I am trying to iterate through the availableData array, if I were to write

v-for="data in availableData[i]"

then is there a way to pass a varaible like i to achieve iteration, or is this method not a plausible way to conduct?

Upvotes: 1

Views: 105

Answers (1)

Thomas Betous
Thomas Betous

Reputation: 5123

You have several solutions to do what you want.

Solution # 1 :

You can alter the availableData to display all data like you want. You have just to flat you array like this : const availableData=[...d1, ...d2];

With such a code your availableData variable will have :

const availableData = [{col1:"aaa1",col2:"bbb1",col3:"ccc1",col4:"ddd1",col5:"eee1"},
          {col1:"aaa2",col2:"bbb2",col3:"ccc2",col4:"ddd2",col5:"eee2"},
          {col1:"fff1",col2:"ggg1",col3:"hhh1",col4:"iii1",col5:"jjj1"},
          {col1:"aaa2",col2:"bbb2",col3:"ccc2",col4:"ddd2",col5:"eee2"}]

Solution # 2

You can make a double iteration in your template :

<div class="data" v-for="data in availableData">
    <div class="row" v-for="row in data">
        <div class="cell">
            {{row.col1}}
        </div>
        <div class="cell">
            {{row.col2}}
        </div>
        <div class="cell">
            {{row.col3}}
        </div>
        <div class="cell">
            {{row.col4}}
        </div>
        <div class="cell">
            {{row.col5}}
        </div>
    </div>
 </div>

Upvotes: 3

Related Questions