繁体   English   中英

如何通过解析 json 的数组访问嵌套数据

[英]How can I access nested data via an array with parsed json

我正在创建一个 vuetify 简单表,它将显示各种数据元素。 问题是,其中一些元素是基于关系和嵌套的。 获取顶级数据很好,如果我将嵌套数据作为独立数据提取,它也可以正常工作。

但是,我想要做的是利用一个数组来避免表格的重复 html 代码。 这可能吗?

下面是为表本身构造的代码。

HTML:

   <v-simple-table fixed-header height="300px">
        <template v-slot:default>
          <thead>
            <tr>
              <th class="text-left">
                Attribute
              </th>
              <th class="text-left">
                Value
              </th>
            </tr>
          </thead>
          <tbody>
            <tr 
            v-for="(serviceProperty, idx) in serviceProperties" 
            :key="idx">
              <th>{{ serviceProperty.label }}</th>
              <td>{{ service[serviceProperty.value] }}</td>
            </tr>            
          </tbody>
        </template>
      </v-simple-table>

JS:

export default {
  name: "Details",
  data() {
    return {
      loading: true,
      service: {},
      serviceProperties: [
        {
          label: 'Description',
          value: 'description'
        },
         {
          label: 'Location',
          value: 'organization.locations[1].streetAddress'
        },        
        {
          label: 'EIN',
          value: 'organization.EIN'
        }
      ]
    };
  },
  props: ["serviceId"],
  async created() {
    this.service = await Vue.$serviceService.findOne(this.serviceId);
    this.loading = false;
  },
};

这似乎不必要地复杂。

考虑使用计算,像这样

...
  computed: {
    mappedData() {
      return this.service.map(item => {
        Description: item.Description,
        Location: item.organization.locations[1].streetAddress,
        EIN: item.organization.EIN
      })
    }
  }
...

然后,您可以通过以下方式访问模板中的数据:

...
<element v-for="item in mappedData">
  {{item.Description}}
  {{item.Location}}
  {{item.EIN}}
</element>
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM