質問

I'm a bit of a novice with JSON. I'm working on building an events page using the JSON feed from last.fm.

The feed is working fine, but the issue is when multiple artists come across for the same event, such as a music festival. Right now the whole array is printing out with no spaces after the commas, and I can't figure out how to shorten the array if many bands are listed. (list the first ten bands, for example.)

The relevant part of my code is

$.getJSON(last_fm_url, function(data) {
  $.each(data.events.event, function(i, item){
    var eventTitle = item.title;
    var eventArtist = item.artists.artist;
  });
});

eventTitle is no big deal since there's only one, but I'm not sure what to do with eventArtist, how to separate that long list into individual items I can work with.

My sample is here: http://bit.ly/ZI4Q5h. My jsfiddle is here: http://jsfiddle.net/SBvUm/2/.

Thank you for your help.

役に立ちましたか?

解決

if you want 10 first items in an array you should use slice

 eventArtist = item.artists.artist.slice(0, 9);

I updated the jsfiddle : http://jsfiddle.net/SBvUm/3/

In order to control that "toString" array representation better, you can use "join".

For example : to get a space after each comma, your final code should look like this

 eventArtist = item.artists.artist.slice(0, 9).join(", ");

The problem you have is that sometimes item.artists.artist is not an array but a string. In this case, slice and join will not work properly.

Your code should look like this

updated the fiddle : http://jsfiddle.net/SBvUm/7/

 var eventArtist = item.artists.artist;
 if ( typeof(eventArtist["join"]) == "function"  ){
      eventArtist = eventArtist.slice(0,9).join(", ");
 }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top