Aindriu
Aindriu

Reputation: 63

Spotify web API results "undefined"

I am trying to get playlists/albums/songs with the Spotify web API. I am able to output to the console these things but if I want to get just the name I get undefined

I am trying to retrieve information by using return data.body.tracks.name

this does not work but I can use

searchSpotify(req, res) {
spotifyApi.searchTracks(req.body.search).then(
  function(data) {
    // var testPage = data.body.tracks.items;
    console.log('Search by user input', data.body.tracks.items);
    res.redirect("/search");
  },
  function(err) {
    console.error(err);
    }
  );
},

Returned Data

this returns some information and as you can see, it also returns a name, how can I access that name to be the only thing I return in my query?

Upvotes: 1

Views: 1098

Answers (2)

Evan Winter
Evan Winter

Reputation: 373

The problem is that items is an array of objects, each of which has a name field.

Try this:

searchSpotify(req, res) {
spotifyApi.searchTracks(req.body.search).then(
  function(data) {
    // var testPage = data.body.tracks.items;
    console.log('Search by user input', data.body.tracks.items);
    const items = data.body.tracks.items
    const names = items.forEach(item => console.log(item.name))
    res.redirect("/search");
  },
  function(err) {
    console.error(err);
  }
);

You should see it print each item's name on a new line.

Upvotes: 0

Shivam
Shivam

Reputation: 3642

data.body.tracks.items returns an array and name is nested inside array then insidealbum object so you have to dive deeper like this

let name = data.body.tracks.items[0].album.name

If you have multiple Items you might have to loop over it, in order to get every name

Upvotes: 1

Related Questions