gauri
gauri

Reputation: 131

Vue js - How to iterate an array inside an array?

I need some dynamic select boxes when given a certain count. For that I have used two arrays -

(i)Array of index (count)
(ii)Array of values.

For first one I have used a v-model (as it need some dynamic input boxes) and second I have just used key and took out its value.

I have tried doing it with single iteration using second array but it failed regression testing.

new Vue({
  el: '#app',
  data: {
    count: 3,
    call: [1, 2, 3],
    sms: [4, 5, 6]
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="app">
  <div class="field">
    <label class="label is-small">Total Count</label>
    <div class="control">
      <input type="text" v-model="count">
      <div class="field" v-for="k in Number(count)">
        <select class="input" v-model="call[k]">
          <option value="" selected>Select Call Hours</option>
          <option v-for="hour in 24">{{hour}}</option>
        </select>
        <select class="input" v-model="sms[k]">
          <option value="" selected>Select SMS Hours</option>
          <option v-for="hour in 24">{{hour}}</option>
        </select>
      </div>
    </div>
  </div>
</div>

This is a part of a form, it works correctly while newly adding data but while editing the values do not appear properly. The first index of call and sms array is left out each time.

Upvotes: 0

Views: 385

Answers (1)

smzapp
smzapp

Reputation: 829

Take note that array starts from 0. So, one way is to subtract k - 1. Example:

sms[k - 1]

new Vue({
  el: '#app',
  data: {
    count: 3,
    call: [1, 2, 3],
    sms: [4, 5, 6]
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="app">
  <div class="field">
    <label class="label is-small">Total Count</label>
    <div class="control">
      <input type="text" v-model="count">
      <div class="field" v-for="k in Number(count)">
        <select class="input" v-model="call[k - 1]">
          <option value="" selected>Select Call Hours</option>
          <option v-for="hour in 24">{{hour}}</option>
        </select>
        <select class="input" v-model="sms[k - 1]">
          <option value="" selected>Select SMS Hours</option>
          <option v-for="hour in 24">{{hour}}</option>
        </select>
      </div>
    </div>
  </div>
</div>

Upvotes: 1

Related Questions