Iterate and fetch a specific quantity of information

I'm seeking a more efficient method to iterate through a JSON object and retrieve a specified number of objects. I am currently manually hardcoding the data retrieval using [] for key-value pairs, but I believe there must be a better approach to accomplish this.

Below is my code snippet:

fetch("https://api.coinmarketcap.com/v2/ticker/?start=0&limit=200")
.then((response) => {return response.json(); })
.then((resp => {
  console.log(resp);
  let price = resp.data;
  showPrice(price);
}))

function showPrice(cryptoPrice) {
  document.querySelector(".results").innerHTML = `
   <div class="container text-center">

     // Repeating structure removed for brevity

   </div>
`;
}
// Styling CSS omitted for brevity
<div class="results"></div>

If you'd like to explore the complete code further, here is a link to the CodePen project: https://codepen.io/Brushel/pen/mjrqXr

Answer №1

https://codepen.io/dennisseah/pen/pZEpQo

fetch("https://api.coinmarketcap.com/v2/ticker/?start=0&limit=200")
  .then(response => {
    return response.json();
  })
  .then(resp => {
    var oData = Object.getOwnPropertyNames(resp.data).slice(0, 20).map(function(i) {
      return resp.data[i];
    });
    displayCryptoInfo(oData);
  });

function displayCryptoInfo(cryptoData) {
  var elements = cryptoData
    .map(function(data) {
      return `<div class="col-4">
      <h1>${data.name}</h1>
      <p><b>Price:</b> <span class="dollar-amount">${
        data.quotes.USD.price
      }</span></p>
      <span><b>Symbol:</b> ${data.symbol}</span>
    </div>`;
    })
    .join("");
  document.querySelector(".results").innerHTML = `
      <div class="container text-center">${elements}</div>`;
}

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

Troubleshooting AngularJS ng-route and Three.js crashes and glitches: A comprehensive guide

I am currently working on a website that utilizes angularjs along with the ng-route directive for navigation between different views. The site also incorporates Three.js for WebGL rendering on canvas. However, I am encountering difficulties as the applicat ...

Can Express not use await?

Why am I encountering a SyntaxError that says "await is only valid in async function" even though I am using await inside an async function? (async function(){ 'use strict'; const express = require("express"); const bodyParser = ...

Obtain the initial element in a table using pure Javascript

There are two tables presented in the following format: <table> <tr> <td></td> <td></td> </tr> </table> <table> <tr> <td></td> <td>&l ...

React Native application fails to return any values from an asynchronous operation in App function

Completely new to React Native, this is my first attempt at coding. I'm struggling with returning jsx from my App() function due to an asynchronous operation within it. Here's the code that I believe clearly demonstrates my issue: import React fr ...

In ReactJS, the process of rendering a functional component differs from that of a class component

I have a class component that looks like this: import { Component } from 'react'; import { DEFAULT_HPP, DEFAULT_PAGE, DEFAULT_QUERY, PARAM_HPP, PARAM_PAGE, PARAM_SEARCH, PATH_BASE, PATH_SEARCH, } from '../../constants'; ...

The date was modified after transforming an object into a string using Jackson JSON serialization

I am a little confused because I need to convert an Object into a json String using the Jackson library. Within my Pojo Class Stage, I have an attribute fromDate of type util.date. public class Stage { @JsonFormat(shape = JsonFormat.Shape.STRING, patter ...

Analyzing the object for interface compatibility

When I receive a query string in one of my REST endpoints using koa-router, each value of the query string object parameter is always a string: { count: "120", result: "true", text: "ok" } Within my codebase, I have an Interface that represents the ...

Is there a way to utilize jquery to click a submit button within a concealed form?

In the current setup, there are 25 products displayed on a single page. Each product contains a form that needs to be dragged to the mini cart located on the right side. The challenge lies in identifying the form ID of the product that is being dragged. T ...

Tips for avoiding HTTP 404 errors when calling a servlet from jQuery using $.ajax

I have been attempting to make an ajax call to a servlet, like so: $.ajax({ url: 'CheckingAjax', type: 'GET', data: { field1: "hello", field2 : "hello2"} , contentType: 'application/json; charset=utf-8', success: fu ...

Is your Vue.js chart malfunctioning?

I have been experimenting with chart.js and vue.js. The component I created is called MessageGraph, and it is structured like this (with data extracted from the documentation): <template> <canvas id="myChart" width="400" height="400">< ...

When ColorField is modified, the color of ScatterLineSeries in Telerik UI for ASP.NET AJAX remains unchanged

I am attempting to customize the color of a ScatterLineSeries in Telerik's RadHtmlChart, but I am facing difficulties as the markers and lines are always displayed with default colors. Despite rewriting my code in different styles, I have not been suc ...

Loop through a range of numbers within an array and retrieve the corresponding values

I am faced with a situation where I need to complete the missing gaps between different week ranges stored in a JSON file. The JSON data looks like this: { "Name": "CHT2578/QGA/YEAR/Practical/01 <5-10, 12-16, 21-25, 27-32>", "Descri ...

Transfer information using cURL without the need to refresh the webpage

I am trying to send data to an external API using cURL from a Facebook iframe page (not tab). However, I want to achieve this without reloading the form page. My idea is to use jQuery AJAX to display a "submitting data" message upon form submission and sh ...

Remove all div elements that do not match the search results using jQuery

Need help with modifying results based on a search value across rows. For this example, let's use 90042 as the search value. Current JavaScript: (function($) { $(document).ajaxComplete(function(e, xhr, settings) { var zi ...

Gather information from various Mongoose requests and forward it to the specified route

Recently embarked on my journey of learning Express with the help of online resources. While I have been able to handle pages dependent on a single query, I have hit a roadblock when it comes to creating a pagination table. In this scenario, I need to exec ...

Aggregate values through an onclick event using a get request and iterate through each using

I am struggling to accumulate values obtained from a json get request using jQuery. The problem is that the values keep getting replaced instead of being added up in the variable total. Can someone please guide me on how to properly sum up the values with ...

Transmitting client-side Javascript data to backend server using Express

I am trying to fetch data from my frontend using the DOM and send it to the backend through Express but I'm unsure of how to proceed. I have used a POST method to console.log the data, but now I need help retrieving it in my Express backend. (The cons ...

Using a combination of JavaScript and ASP.NET, you can easily toggle the functionality of buttons

I am trying to determine if a user exists in the database. If the user exists, I want to display a message stating "existing user" and then disable the signup button. If the user does not exist, I want to enable the signup button. However, I am encounteri ...

Using various hues for segmented lines on ChartJS

I am working with a time line chart type and I want to assign colors to each step between two dots based on the values in my dataset object. In my dataset data array, I have added a third item that will determine the color (if < 30 ==> green / >3 ...

Execute a second ajax function in Jquery only when the first ajax function has finished its execution entirely

Currently, I am dealing with 2 ajax calls in separate functions. My goal is to trigger both of these functions using .click. The first function (func1) inserts data into the database, while the second function (func2) retrieves this data. But my main conce ...