Home > Enterprise >  Limit JSON results in array [duplicate]
Limit JSON results in array [duplicate]

Time:09-29

I am calling some JSON results which lists a bunch of actors in an array named 'cast'. I am calling the first item from that list with this JS...

let movieCredits = document.getElementById("movieCredits");
movieCredits.innerHTML = out.credits.cast[0].name;

And displaying them in a div like this...

<div id="movieCredits"></div>

I need to list the first 5 results (not just the first). Is their a simple way to do this?

CodePudding user response:

You can create a new array with the first 5 results using Array.slice:

const firstFive = out.credits.cast.slice(0, 5)

You could then generate HTML from it, depending on what you want to do, e.g.

const listItems = firstFive.map(actor => `<li>${actor.name}</li>`);
movieCredits.innerHTML = `<ul>${listItems}</ul>`;

CodePudding user response:

Your code explicitly references only element 0 of your array... you need to be able to reference the first 5. Then, with the one you reference, you're setting the innerHTML to that one thing... as you currently do, even if you loop through array you'll keep overwriting the innerHTML. You either need to build a single string of innerHTML as you loop and then do a final write... OR, create new HTML elements as you loop and add them as children to your target div as Ive done in the snippet below.

function populateCast() {

  var out = {};
  out.credits = {};
  out.credits.cast = [{
      name: 'actor_one'
    },
    {
      name: 'actor_two'
    },
    {
      name: 'actor_three'
    },
    {
      name: 'actor_four'
    },
    {
      name: 'actor_five'
    },
    {
      name: 'actor_six'
    },
    {
      name: 'actor_seven'
    }
  ];

  for (var i = 0; i < 5; i  ) {
    var element = document.createElement("p");
    element.innerHTML = out.credits.cast[i].name;
    var target = document.getElementById('movieCredits');
    target.appendChild(element);
  }
}
<html>

<body>
  <div id="movieCredits"></div>
  <button id="castPopulate" onClick="populateCast()">Populate Cast</button>
</body>

</html>

  • Related