Home > Blockchain >  Iterating through grouped object data in Vue
Iterating through grouped object data in Vue

Time:10-14

My data comes from an API as follows

{
   "ALBUMS":[
      {
         "ID":"1",
         "TITLE":"'THE BEST OF"
      },
      {
         "ID":"2",
         "TITLE":"MADE IN ENGLAND"
      },
   ],
   "PLAYLISTS":[
      {
         "ID":"5",
         "TITLE":"SUNSET SESSIONS"
      },
       "ID":"2",
         "TITLE":"POOLSIDE SESSIONS"
      }
   ],
}

I want to list all titles and types (album or playlist).

The following that I came up with only gives me the first child from albums and playlists:

<div v-for="(item, index) in items" :key="item.id">
 <h1 class="category">{{index}}</h1>
 <h1 class="title">{{item[0].title}}</h1>

My desired result would be:

Album
The Best Of

Album
Made In England

Playlist
Sunset Sessions

Playlist 
Sunset Sessions

CodePudding user response:

Looks like you were missing the second level of your data hierarchy. See the following snippet for an example of how it might work with the data you've provided

new Vue({
  el: "#app",
  data: {
   "ALBUMS":[
      {
         "ID":"1",
         "TITLE":"'THE BEST OF"
      },
      {
         "ID":"2",
         "TITLE":"MADE IN ENGLAND"
      },
   ],
   "PLAYLISTS":[
      {
         "ID":"5",
         "TITLE":"SUNSET SESSIONS"
      },
      {
         "ID":"2",
         "TITLE":"POOLSIDE SESSIONS"
      }
   ],
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
   <div v-for="album in ALBUMS" :key="album.ID">
   <strong>Album</strong>
     {{album.TITLE}}
   </div>
   <div v-for="playlist in PLAYLISTS" :key="playlist.ID">
     <strong>Playlist</strong>
     {{playlist.TITLE}}
   </div>
</div>

  • Related