Creating a dropdown menu in Vue.js with a nested array

Upon receiving a response from the Zoho API, I am faced with an array structured as follows:


{
    "response": {
        "result": [{
            "4076840000001": [
                {
                    "Department": "Department 1",
                    "Department_Lead.ID": "4076840000001"
                    ...
                }
            ]
        }, 
        {
            "40768400000012": [
                {
                    "Department": "Department 2",
                    "Department_Lead.ID": "40768400000011",
                    ....
                }
            ]
        },
        {
            "407684000000125": [
                {
                    "Department": "Department 3",
                    "Department_Lead.ID": "40768400000011233",
                    ....
                }
            ]
        }],
        "message": "Data fetched successfully",
        "uri": "/api/forms/department/getRecords",
        "status": 0
    }
}

The specific array of interest in this case is response.result. It is assigned to a variable as shown below:


vm.allDepartments = JSON.parse(data.Payload).response.result

My goal is to populate a dropdown menu where the department ID serves as the value and the Department name is displayed. Given that each department is within an object nested in an array, I believe two v-for loops are necessary. Since there should always be only one object in each array (in the event of multiple objects, I require the first object's Department name), I attempted to achieve this using the following code snippet:


   <select v-model="department">
        <div v-for="department in allDepartments">
          <option
            v-for="(value, key) in department"
            :value="key">{{value[0]['Department']}}</option>
        </div>
    </select>

However, after implementing this code, my dropdown menu does not display any options when viewed on the frontend. Strangely enough, upon inspecting the code, I can see that the options are indeed present.


<select class="form-control" id="__BVID__105_">
    <div>
        <option value="4076840000001">Department 1</option>
    </div>
    <div>
        <option value="40768400000012">Department 2</option>
    </div>
    ....

This issue could potentially stem from the surrounding div tag enclosing the option tags. Unfortunately, despite being new to Vue.js, I have not been able to find a solution for this problem. Any assistance or guidance would be greatly appreciated.

Answer №1

Avoid using div and opt for the template element instead.

<select v-model="department">
  <template v-for="department in allDepartments">
    <option v-for="(value, key) in department"
            :value="key">{{value[0]['Department']}}</option>
  </template>
</select>

console.clear()

const response = {
  "response": {
    "result": [{
      "4076840000001": [{
        "Department": "Department 1",
        "Department_Lead.ID": "4076840000001"
      }]
    }, {
      "40768400000012": [{
        "Department": "Department 2",
        "Department_Lead.ID": "40768400000011",
      }]
    }, {
      "407684000000125": [{
        "Department": "Department 3",
        "Department_Lead.ID": "40768400000011233",
      }]
    }],
    "message": "Data fetched successfully",
    "uri": "/api/forms/department/getRecords",
    "status": 0
  }
}

new Vue({
  el: "#app",
  data:{
    department: null,
    allDepartments: response.response.result
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div id="app">
  <select v-model="department">
    <template v-for="department in allDepartments">
      <option v-for="(value, key) in department"
              :value="key">{{value[0]['Department']}}</option>
    </template>
  </select>
  <hr>
  {{department}}
</div>

The template element is especially useful for creating groupings without rendering an actual element, making it ideal for loops in Vue applications.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Invoking a nested method within Vue.js

I am facing an issue in my vuejs application with 2 methods. When I define method1 a certain way, it does not run as expected. method1: function(param1, param2){ // I can log param1 here thirdLib.debounce(function(param1, params2){ // It d ...

Exploring the variations in method declarations within Vue.js

Today, while working with Vue, I came across an interesting observation. When initially using Vue, there were two common ways to define a method: methods: { foo: () => { //perform some action } } and methods: { foo() { / ...

Using Vue.js, you can set a method to return data directly to

Having just begun my journey with Vue, I find myself in a bit of a predicament. As part of my learning process, I am developing an app for tracking episodes in TV series. The initial step involves searching for series and adding them to a database. When co ...

Retrieve the object filtered by a specific group from an array of data

I have a data object that contains various groups and rules within each group item. My task is to filter the rules based on a search query, while also displaying the group name associated with the filtered rule. { "id": "rulesCompany", "group": [ ...

Enhancing data management with Vuex and Firebase database integration

Within my app, I am utilizing Firebase alongside Vuex. One particular action in Vuex looks like this: async deleteTodo({ commit }, id) { await fbs.database().ref(`/todolist/${store.state.auth.userId}/${id}`) .remove() .then ...

Is it possible to generate unique identifiers for v-for keys using vue-uuid?

I'm attempting to utilize a random string (UUID v4) using vue-uuid for existing items and future additions to the list in my to-do list style application. However, I'm uncertain about the correct syntax to use. After installation, I included it ...

Setting a default date dynamically for v-date-picker in the parent component, and then retrieving the updated date from the child component

I'm working with a custom component that utilizes the v-date-picker in various instances. My goal is to have the ability to dynamically set the initial date from the parent component, while also allowing the date to be modified from the child componen ...

Utilizing Vue and Vuex to execute Axios operations within a store module

Currently, I am developing an application in Vue that utilizes Vuex for state management. For CRUD operations on the data, I have implemented Axios. The issue arises when, for example... I make a POST request to my MongoDB database through an Express ...

Vue router is unable to render or mount the component at the root path

I am currently working on a webpage using vue, vue-router, and laravel. I have encountered an issue where the Home component is not being rendered in the router-view when I access localhost/myproject/public_html/. However, if I click on the router link to ...

Copy password input field content in Vue to clipboard

I'm currently working on a Vue app that includes a form input for creating passwords. I've managed to implement a button that shows/hides the password, but I'm struggling with adding a copy to clipboard function. It doesn't seem to be w ...

Using Vue.js to bind labels and radio buttons in a form

My goal is to generate a dynamic list of form polls based on the data. However, using :for or v-bind:for does not result in any HTML markup appearing in the browser, causing the labels to not select the corresponding input when clicked. I have prepared a J ...

Mastering the art of tab scrolling in VueJS using Bootstrap-vue

Currently, I am working on a VueJS project that utilizes bootstrap-vue. The issue I am facing is that when rendering a list of tabs, it exceeds the width of its parent container. To address this problem, I aim to implement a solution involving a set of but ...

VueJS does not update values instantly as they change

I have implemented a JS class with the following code: class Field { public Value = null; public Items = []; public UniqueKey = null; public getItems() { let items = [...this.Items]; items = items.filter((item) => { ...

When the state changes, initiate the animation

Currently, I am working with Vue.js and need to animate a navigation menu. My goal is to display two li elements when a user hovers over one of the navigation buttons. At the moment, I have set the data type showActivities to false by default and changed ...

Vue js version 2.5.16 will automatically detect an available port

Every time I run the npm run dev command in Vue.js, a new port is automatically selected for the development build. It seems to ignore the port specified in the config/index.js file. port: 8080, // can be overwritten by process.env.PORT, if port is in u ...

Exploring the capabilities of a Vue.js component

I am currently facing some challenges while trying to test a Vue.js component. My main issue lies in setting a property for the component and verifying that it has been set correctly. For context, the module has been loaded with exports and the JavaScrip ...

What is the best way to display HTML code using Vue syntax that is retrieved from an Axios GET request

I am currently working on a project that involves a Symfony 5 and Vue 3 application. In this setup, a Symfony controller creates a form and provides its HTML through a JSON response. The code snippet below shows how the form HTML is returned as a string: i ...

What seems to be the issue with the data initialization function not functioning properly within this Vue component?

In my Vue 3 component, the script code is as follows: <script> /* eslint-disable */ export default { name: "BarExample", data: dataInitialisation, methods: { updateChart, } }; function dataInitialisation() { return { c ...

looking to display the latest status value in a separate component

I am interested in monitoring when a mutation is called and updates a status. I have created a component that displays the count of database table rows when an API call is made. Below is the store I have implemented: const state = { opportunity: "" } ...

Vue - Passing a parent's ref to a child component as a prop

Is there a way to pass the current component's reference to a child component in Vue.js? <template> <div class="screen" ref="screen"> <child-component :screenRef="screenRef"> </child-component> </div ...