Atif Şeşu
Atif Şeşu

Reputation: 125

Vue auto select checkbox according to another array

So i have 2 different api request in my vue application. One of them is bringing the all questions.

[ { "id": 20, "question": "Cigarette" }, { "id": 2, "question": "Alcohol" }, { "id": 3, "question": "Diabetes" }]

In second request is returning what client has checked from the form about these questions.

{ "cigarette": "yes", "alcohol": "yes", "mobile": "+44111111111"}

and so on...

In my form.js file i want to see the checkbox has checked if client has selected that checkbox. In for loop i have this

<li v-for="(ask, askey) in patientQuestions" :key="askey">
    <b-form-checkbox v-model="ask.value">{{ ask.question }}</b-form-checkbox>
</li>

How can i auto select this checkboxes. Thanks in advance

Upvotes: 1

Views: 360

Answers (1)

Brother Woodrow
Brother Woodrow

Reputation: 6372

It's more difficult than it needs to be because you need something to relate the answer to the question. You'd want something that's the same in both cases and you don't really have that right now. The answers key and question text almost match, but one is lowercase and the other one is not. It would be easier/more reliable if you could for example get the question ID in the answer object.

Given your current data structure, you could do this:

<div id="app">
  <ul>
    <li v-for="(pq, index) in patientQuestions" :key="pq.id">
      <b-form-checkbox value="yes" v-model="answers[pq.question.toLowerCase()]">{{ pq.question }}</b-form-checkbox>
    </li>
  </ul>
</div>

var app = new Vue({
  el: '#app',
  data: {
    patientQuestions: [{
        "id": 20,
        "question": "Cigarette"
      },
      {
        "id": 2,
        "question": "Alcohol"
      },
      {
        "id": 3,
        "question": "Diabetes"
      }
    ],
    answers: {
      "cigarette": "yes",
      "alcohol": "yes",
      "mobile": "+44111111111"
    }
  }
})

Fiddle: https://jsfiddle.net/thebluenile/1bheo648/

Upvotes: 1

Related Questions