freddyal
freddyal

Reputation: 25

Displaying all the items in an array using jquery and json

I am trying to get all the items in an array to show using json and jquery from the song of ice and fire api. I can only get one item to show from each of the arrays.

Here is the codepen: https://codepen.io/frederickalcantara/pen/aWeXOz

var data;

$.getJSON(characters[i], function(json) {
    data = json;

    var alliance = $('#alliance');
    for (var i = 0; i < data.allegiances.length; i++) {
        if (i === data.allegiances.length - 1) {
            $.getJSON(data.allegiances[i], function(json1) {
               alliance.html(json1.name);
            });
        } else {
            $.getJSON(data.allegiances[i], function(json1) {
               alliance.html(json1.name + ', ');
            });
        }

    }

    const title = $('#title');

    if (data.titles.length === "") {
        return 'N/A';
    } else {
        for (i = 0; i < data.titles.length; i++) {

            if (i === data.titles.length - 1) {
                title.html(data.titles[i]);
            } else {
                title.html(data.titles[i]) + ', ';
            }

        }


    const tv = $('#seasons');

    for (var i = 0; i < data.tvSeries.length; i++) {
        if (i === data.tvSeries.length - 1) {
            tv.html(data.tvSeries[i]);
        } else {
            tv.html(data.tvSeries[i] + ', ');
        }
    }

    const actor = $('#actors')
    if (json.playedBy === "") {
        return 'N/A';
    } else {
        actor.html(json.playedBy);
    }

});

Upvotes: 1

Views: 44

Answers (1)

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

The main problem is your loop. You keep replacing the value in the html element until the last value in the array. You can simplify this code like this:

  title.html(data.titles.join(','));

which replaces all of this:

 for (i = 0; i < data.titles.length; i++) {

        if (i === data.titles.length - 1) {
            title.html(data.titles[i]);
        } else {
            title.html(data.titles[i]) + ', ';
        }

    }

Update: Handling the allegiances. Using a Promise here is important because you are making a number of AJAX calls and you need to be sure that they are resolved before attempting to display them. You can replace the entire for loop for the allegiances like this:

  Promise.all(data.allegiances.map(function(ally){
     return new Promise(function(resolve, reject){
         $.getJSON(ally, function(json) {
               resolve(json.name);
         });
     });
   }))
   .then(function(allies){
     alliance.html(allies.join(', '));
   });

Upvotes: 1

Related Questions