Home » vue » How to populated Vue drop down with nested objects

How to populated Vue drop down with nested objects

Posted by: admin November 26, 2021 Leave a comment

Questions:

l have this json response and want to populate "name" with drop down Vue

{
    "code": 200,
    "message": "OK",
    "payload": [
        "grade",
        [
            {
                "id": 1,
                "name": "B",
                "desc": "test test test"
            }
            {
                "id": 2,
                "name": "B",
                "desc": "test test test"
            }
           
        ]
    ]
}
Answers:

Do you want to achieve something like this?

You can do that if you use a v-for and fill the values dynamically in the select option. So no matter what your payload looks like you can put the contents in your dropdown.

Vue.createApp({
  data() {
    return {
     selectedName: '',
     payload: [
        [
         {
           "id": 1,
           "name": "John Doe"
         },
         {
            "id": 2,
            "name": "Elvis Presley"
         }  
      ]
    ]
  }
 }
}).mount('#select-name')
.demo {
  font-family: sans-serif;
  border: 1px solid #eee;
  border-radius: 2px;
  padding: 20px 30px;
  margin-top: 1em;
  margin-bottom: 40px;
  user-select: none;
  overflow-x: auto;
}
<script src="https://unpkg.com/[email protected]"></script>

<div id="select-name" class="demo">
  <select v-model="selectedName">
    <option value="" disabled hidden>select a name</option>
    <option v-for="user in payload[0]" :value="user.name">
      {{ user.name }}
    </option>
  </select>
  <br>
  <span>name: {{ selectedName }}</span>
</div>

Look at the official example to understand what is happening there.