0

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?

lowercase
  • 1,198
  • 9
  • 34
  • 56
  • JSON is a textual representation of data. If you can access the data using `out.credits.cast[0].name` then this data isn't JSON, but data that has already been parsed and represented as Objects, Arrays, and primitive values. – t.niese Sep 28 '21 at 20:57
  • JSON results as per title. – lowercase Sep 28 '21 at 21:00

2 Answers2

1

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>`;
Marcel Herd
  • 392
  • 1
  • 8
  • Like this? movieCredits.innerHTML = out.credits.cast.slice(0, 5).name; That doesn't work...undefined. – lowercase Sep 28 '21 at 20:57
  • That would try to access the name property on an Array - you want to access the name property on each array element. Check out my edit. @lowercase – Marcel Herd Sep 28 '21 at 20:58
1

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>
DynasticSponge
  • 1,416
  • 2
  • 9
  • 13