I am working on a JavaScript web app that takes input from a user (the name of a musical artist) and outputs a list of related artists and their most popular song, as determined by the Spotify API. I initially had a rudimentary version of this functioning, but it would just post a list of all the related artists with a list of those related artists' most popular songs immediately above it, and I want the entire object to print out (artist plus most popular song).
I have a series of objects representing the artists that I received through the spotify-web-api-js node module with Node.js and Browserify to make it function on the browser, uniquely identified by their Spotify ID. How can I loop through them if I don't know those IDs in advance before a user does a search so that I can properly push them into an object that I can then input to the DOM through jQuery's append
? I've been trying to access them in various ways, but it doesn't seem to be working:
s.getArtistRelatedArtists(originalArtistId, function(err, data) {
for (i = 0; i < data.artists.length; i++)
{
console.log(data.artists[i].name);
relatedArtistsObject[data.artists[i].id] = {
name: data.artists[i].name,
songs: []
};
s.getArtistTopTracks(data.artists[i].id, "US", function (err, data2) {
if (relatedArtistsObject[data2.tracks[0].artists[0].id] !== undefined)
{
// console.log(data2.tracks[0].name); -- this outputs the song titles I want
relatedArtistsObject[data2.tracks[0].artists[0].id].songs.push(data2.tracks[0].name);
}
});
}
console.log(relatedArtistsObject);
// loop through this object and print it through the screen
for (k = 0; k < relatedArtistsObject.length; k++)
{
console.log(relatedArtistsObject.id.songs[0].name);
$('#related-artist').append(relatedArtistsObject[k]);
}
// $('#related-artist').append(relatedArtistsObject);
});
Here is a link to the full code (not functioning because it doesn't have Node.js/browserify enabled): https://jsfiddle.net/pmh04e99/
This answer is partially helpful, but doesn't apply here because the JSON output doesn't have a "name" field in the array I want to access. Instead, songs
is an array of 1, and the content I want is within item 0
. My console.log output of the relatedArtistsObject
looks like this, for example:
How can I access these objects in the DOM through my code when I don't know the spotify IDs right now?
Note: I'm aware that i'm not error handling yet, but I want to be able to implement the main functionality first.