Iterate array with different start and end points

Viewed 4520

How do you iterate over an json array with different start and endpoint.

e.g. say a list of 20 items..

I want to iterate the list in 0-4, 5-9, 10-14, 15-19...

I've tried the v-for syntax with different options but cant get it working.

  <tr v-for="(user, index) in json.users">

I want users[0] to users[4] in first loop, then users[5] to users[9] in second loop etc...

I dont want to iterate the whole loop at once. I need to oterate it in split sections.

3 Answers

You could slice the array in the template:

<div v-for="item in items.slice(0, 4)>
  {{ item }}
</div>

Here's an example:

new Vue({
  el: '#app',
  data() {
    return {
      items: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
    }
  }
})
ul { border: 1px goldenrod solid; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <ul v-for="i in 5">
    <li v-for="item in items.slice((i-1)*5, (i-1)*5+5)">
      {{ item }}
    </li>
  </ul>
</div>


Alternatively, you could create a computed property to structure your data in a way that would be easier to display:

new Vue({
  el: '#app',
  data() {
    return {
      items: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
    }
  },
  computed: {
    sections() {
      let sections = [], size = 5;
      let items = [...this.items];

      while (items.length > 0)
        sections.push(items.splice(0, size));
        
      return sections;
    }
  }     
})
ul { border: 1px goldenrod solid; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <ul v-for="items in sections">
    <li v-for="item in items">
      {{ item }}
    </li>
  </ul>
</div>

Use v-for range and slice.

Vuejs support v-for with a range.

https://v2.vuejs.org/v2/guide/list.html#v-for-with-a-Range

<div v-for="n in (items.length / 5)">
  <div v-for="item in items.slice(n*5, n*5 + 5)>
    {{ item }}
  </div>
</div>

Note that the following code it not complete and you need to fix it when the list is not a multiple of 5.

Related