Wednesday, 31 May 2017

How to iterate thru an object that has an array using pug?

I'm working on this side project which involves Nodejs and spotify web api node to make requests to search artists. I get the json response back and its an object with arrays inside it for example:

{ "artists" : { "href" : "https://api.spotify.com/v1/search?query=drake&type=artist&market=US&offset=0&limit=20", "items" : [ { "external_urls" : { "spotify" : "url" }, "followers" : { "total" : 10302826 }, "genres" : [ "canadian pop", "hip hop", "pop rap", "rap" ], "href" : "url", "id" : "3TVXtAsR1Inumwj472S9r4", "images" : [ { "height" : 640, "url" : "url", "width" : 640 }, { "height" : 320, "url" : "url", "width" : 320 }, { "height" : 160, "url" : "url", "width" : 160 } ], }

What I have in my app.js to get the url is this:

 var link = data.body.artists.items[0].images[0].url;
 res.render('artist', {
      info: data.body,
      url: link
    });

but I cannot use that same idea on my index.pug instead of having to use a variable like this:

for (var i = 0; i < 20; i++) {
     .col-md-3
          .well.text-center
            h4= info.artists.items[i].name
            img(src= **info.artists.items[i].images[0].url**)
}

I get an error, url cannot be defined. Furthermore, how could I iterate thru an object like this. I tried each a in info and instead of having a static 20 I tried info.artist.items.length which return a number but only in my app.js not in pug.



via Carlos Cancino

No comments:

Post a Comment