简体   繁体   中英

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

I am creating a vuetify simple table that is going to display various data elements. The problem is, some of those elements are based on relationships and nested. Getting the top level data is fine, and if I pull the nested data as a standalone, it works fine as well.

However, what I want to do is utilize an array to avoid repetitive html code for the table. Is this possible at all?

Below is the code as constructed for the table itself.

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;
  },
};

This seems unnecessarily complicated.

Consider using computed, like this

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

You can then access the data in the template with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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