Search code examples
vue.jsdropdownv-for

Loop through a complex object of array in vue to get a particular field populated in dropdown


This is my object i want to loop through

{
"_msgid":"22343sadda",
"payload":
   {
   "@status":"green",
   "@code":"19",
   "result":
        {
        "@total-count":"2",
         "@count":"2",
          "entry": 
             [{
              "@id":"abc123",
              "@location":"vcfa"
              },
              {
             "@id":"ftef",
               "@location":"562532"
                }]
        }
    }
}

This is my frontend where i just want @id to be populated in dropdown

<bc-dropdown label="Dropdown object"  v-model="form.location" @select="getGroups">
<bc-dropdown-option v-for="g in groupOptions"  :key="g._msgid" :value="g">
  </bc-dropdown-option>
  </bc-dropdown>

This is the method which gives me the object in return

getGroups() {
            axios.get("api/getGroups").then((response) => {
                this.groupOptions= response.data;
                console.log("groups", this.groupOptions);
            }).catch(error => {
                console.log(error);
                console.log(error.response.data);
                console.log(error.response.headers);
            });

Currently i am getting entire object in dropdown. Kindly help me with the proper code to just populate @id from return object

Updated:

I want populate @name in the dropdown


Solution

  • Your dropdown options array is response.data.payload.result.entry not response.data.

    Working Demo :

    new Vue({
        el: '#app',
        template: `
            <div>
                <select v-model="selectedEntry">
                    <option v-for="entry in payload.result.entry" :value="entry['@id']">{{entry['@location']}}</option>
                </select>
                <h4>Selected Entry: {{selectedEntry}}</div>
            </div>
        `,
        data: {
            payload: {
                result: {
                entry: [{
                  "@id":"abc123",
                  "@location":"vcfa"
                }, {
                    "@id":"ftef",
                  "@location":"562532"
                }]
              }
            },
            selectedEntry: ""
        }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app"></div>