Restrict the amount of JSON data returned within an array

My script fetches JSON data and extracts a list of actors stored in an array called 'cast'. To display the first actor from this list, I use the following JavaScript...

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

The actor information is then shown in a div like so...

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

I want to display the first 5 results instead of just the first one. Is there an easy way to achieve this?

Answer №1

To extract the first 5 elements from an array, you can use the Array.slice method:

const initialFive = myArray.slice(0, 5)

After that, you have the option to generate HTML content based on your specific requirements. For example:

const itemsList = initialFive.map(element => `<li>${element}</li>`);
document.getElementById("output").innerHTML = `<ul>${itemsList}</ul>`;

Answer №2

Your current code is only referencing the first element in your array, but you need to access the first 5 elements. Also, by setting innerHTML within a loop, you are constantly overwriting it. To solve this issue, you can either build a string of innerHTML as you loop and then write it at once, or create new HTML elements and append them as children to your target div like I've demonstrated in the example 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The YouTube Iframe API encountered an issue while attempting to send a message to an HTTP recipient. The recipient's origin

Encountering an error when using the YouTube Iframe API on Safari 9.1, OS X Yosemite Issue: Unable to post message to http://www.youtube.com. Recipient has origin https://www.youtube.com This problem only occurs in Safari, as other browsers like Firefo ...

Warning: Shadcn-UI Form Alert - An element is converting an uncontrolled input to controlled mode

Throughout the course of this project, I found myself repeatedly using const [fileNames, setFileNames] = useState<string[]>([]); and logging the state with console.log(fileNames). However, every time I clicked on the parent element, an empty Array e ...

A method for applying the "active" class to the parent element when a child button is clicked, and toggling the "active" class if the button is clicked again

This code is functioning properly with just one small request I have. HTML: <div class="item" ng-repeat="cell in [0,1,2]" data-ng-class="{active:index=='{{$index}}'}"> <button data-ng-click="activate('{{$index}}')">Act ...

Vue - unable to display component CSS classes in application when using class-style bindings

Just diving into Vue and starting with class-style binding syntax. I'm facing an issue where the CSS classes for header and footer that I've defined are not displaying, even though I've referenced them in the component tags. Can't seem ...

Interacting with Django backend via AJAX to trigger Python functions using jQuery/AJAX

Currently, I am developing a small website using Django. Within this project, there are DateTime fields that need to be handled. My intention is to utilize ajax by implementing another button to establish the UTC date while taking into consideration sola ...

display JSON data beautifully on a webpage using Express

I am trying to display a large JavaScript object in a visually appealing format on my browser window using Express. I have experimented with using res.json() and res.send() with pretty print enabled in Express, but it seems that this method only works fo ...

From Python CSV to JSON: Exploring the size disparity between JSON and CSV files and possible solutions

Encountered an intriguing issue while converting a CSV file to JSON. The process involves generating a CSV file based on output from a SQLite query and saving it to the hard drive. To work with the CSV file, I use Pandas in my script: import pandas as pd ...

Error encountered while scrolling with a fixed position

I am currently in the process of developing a carousel slider that resembles what we see on Android devices. The main challenge I am facing at this early stage is applying the CSS property position: fixed; only horizontally, as vertical scrolling will be n ...

Generate a fresh Date/Time by combining individual Date and Time components

I have set up a form to gather dates from one input box and times from another. var appointment_date = new Date(); var appointment_start = new Date("Mon Apr 24 2017 20:00:00 GMT-0400 (EDT)"); var appointment_end = new Date("Mon Apr 24 2017 21:30:00 GMT- ...

Dealing with CORS, IIS7, and PHP - Overcoming the Access-Control-Allow-Origin obstacle

I am attempting to enable another local host (such as javascript.dev) to make a xhr request to this particular host, which operates on an IIS7 server. When I perform a curl -I command, the headers I receive are as follows: HTTP/1.1 200 OK Content-Length: ...

Using jQuery to send a post request to a PHP script using either JavaScript or PHP

Just a quick question for those with experience. I am working on a page where I have implemented a jQuery AJAX post to another PHP page that contains JavaScript. My concern is, will the JavaScript code also be executed? Another scenario to consider is if ...

difficulty with JSON format

I'm currently working on an app that relies on JSON. I'm utilizing the link https://maps.googleapis.com/maps/api/place/autocomplete/json?input=+place+&types=geocode&sensor=true&key=AIzaSyCA4LKD6QfiCrGhZjCsYiRyEGqxKOUEQBU. In this link ...

Delete elements with identical values from array "a" and then delete the element at the same index in array "b" as the one removed from array "a"

Currently, I am facing an issue while plotting a temperature chart as I have two arrays: a, which consists of registered temperature values throughout the day. For example: a=[22.1, 23.4, 21.7,...]; and b, containing the corresponding timestamps for eac ...

How can I save a value in JavaScript once the page has finished loading?

$("#divid1").click(function(){ $("#divid1").hide(); //this should remain hidden even after refreshing the page $("#hideid1").hide(); //this should remain hidden even after refreshing the page $("#id1").show(); //this should remain visible even ...

Using double quotation marks at the end of AngularJS expressions can cause issues

Upon stumbling across a popular answer with +50 upvotes and an intriguing comment, I learned about a unique way to define Angular variables in templates without having them rendered as text. By simply ending the expression with a semicolon and double quote ...

Combining model with a string in an expression in AngularJS version 1

Can this text be transformed into an expression using ecmaScript 2015? The || operator seems to be causing issues. {{ ::$ctrl.realEstateProjectCurrentProduct.housingTax + ' €' || $ctrl.noDataMessage }} ...

Developing a customized ResourceConfig that mimics the default Jetty's Jersey registration process

I am currently working on an endpoint implementation that looks like this: @POST @Path("/test") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String canaryTest(String JSON) { return JSON; } When I integrate this e ...

Manipulating data in a deeply nested field of an embedded document using Mongoose, MongoDB, and Express

I have been pondering whether it is feasible to input data into the comments field of my "TopicSchema": var mongoose = require('mongoose'); var TopicSchema = new mongoose.Schema({ username: String, topic: String, des ...

Craft a JavaScript script (empowered by selenium) that endures through page reloads

In the process of developing a macro recording and playback system utilizing selenium and JavaScript, I encountered an issue. Essentially, I have implemented a JavaScript code that attaches a new event handler to all window events, capturing and storing ev ...

The AJAX error message shows that the function checkUsn is not defined when an HTMLInputElement.onkeyup

I'm currently developing a login form that is connected to a MySQL database and I'm trying to implement a feature where I can check if a username exists in the database without having to reload the entire page. I'm utilizing Ajax to send and ...