循环遍历 vue 中的复杂数组对象以获取下拉列表中填充的特定字段

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

这是我要循环的对象

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

这是我的前端,我只想在下拉列表中填充@id

<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>

这是在 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);
            });

目前我正在下拉列表中获取整个对象。请帮助我使用正确的代码从 return object

中填充 @id

已更新:

我想在下拉列表中填充@name

您正在将 this.groupOptions 设置为您正在获取的对象。您需要解析对象并获取要循环的数组。

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

由于 this.groupOptions 现在是对象数组,您可以将值设置为等于 @id 字段。由于 属性 名称具有特殊字符,您必须使用括号表示法才能访问它。

<bc-dropdown label="Dropdown object"  v-model="form.location" @select="setGroup">
  <bc-dropdown-option v-for="g in groupOptions"  :key="g['@id']"  :value="g['@id']" />
</bc-dropdown>

您的下拉选项数组是 response.data.payload.result.entry 而不是 response.data

工作演示:

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>