I am taking data from a JSON file and using javascript so I can display it on a web page. The json file contains data on a movie cast. Each movie cast has a name, id and characters they play (some play more than one character).
"abridged_cast":[
{"name":"Tom Hanks","id":"162655641","characters":["Woody"]},
{"name":"Tim Allen","id":"162655909","characters":["Buzz Lightyear"]},
{"name":"Joan Cusack","id":"162655020","characters":["Jessie the Cowgirl"]},
{"name":"Ned Beatty","id":"162672460","characters":["Lots-o'-Huggin' Bear","Lotso"]},
{"name":"Don Rickles","id":"341817905","characters":["Mr. Potato Head"]}
],
I want to display the cast on the web page as follows: Starring: Tom Hanks as Woody, Tim Allen as Buzz Lightyear, Joan Cusack as Jessie the Cowgirl, Ned Beatty as Lots-o'-Huggin' Bear & Lotso, Don Rickles as Mr. Potato Head.
What I am getting: Starring: Tom Hanks as & Woody, Tim Allen as & Buzz Lightyear, Joan Cusack as & Jessie the Cowgirl, Ned Beatty as Lots-o'-Huggin' Bear, & Lotso, Don Rickles as & Mr. Potato Head,
I only want an "&" if the actor plays more than one character and between the last and second last characters. Forr example: Starring: John as Tiger, Lion, Tree & Crow.
I have spent ages trying to figure if out and I really cannot see what I am doing wrong. Here is my javascript:
$(document.body).append('<strong>Starring:</strong> ');
for (var i = 0;i < movie.abridged_cast.length; i++){
$(document.body).append(movie.abridged_cast[i].name + " as ");
for (var j = 0; j < movie.abridged_cast[i].characters.length; j++){
if(movie.abridged_cast[i].characters[j] == movie.abridged_cast[i].characters[movie.abridged_cast[i].characters.length -1]
// if the character = the character in the last position
&& movie.abridged_cast[i].characters[j].length -1 > 0){
// and the position of the character is greater than 0
$(document.body).append('& ' + movie.abridged_cast[i].characters[j] + ', ');
}
else {
$(document.body).append(movie.abridged_cast[i].characters[j] + ', ');
}
}
}