Guide to fetching and displaying a complex array API using JavaScript's fetch method

Recently, I've been delving into the world of APIs and making sure I call them correctly. Using the fetch method has been my go-to so far, and here's a snippet of the code where I reference an API:

  fetch('https://datausa.io/api/data?drilldowns=Nation&measures=Population')
            .then(function (response) {
                return response.json();
            })
            .then(function(data) {
                appendData(data);
            })
            .catch(function(err) {
                console.log('error: ' + err);
            });
        function appendData(data) {
            var mainContainer = document.getElementById("myData");
                var div = document.createElement("div");
                div.innerHTML = 'Name: ' + data[0].Population;
                mainContainer.appendChild(div);
           // }
        }
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JSON Test</title>
</head>
<body>
    <div id="myData"></div>
</body>
</html>

The goal is to retrieve the "Population" data for 2019 and showcase it. While dealing with simple APIs that do not involve arrays or complex structures, it's relatively straightforward. However, in this case, I seem to be struggling with differentiating between arrays and objects while coding it - any tips or suggestions on how to tackle this?

Answer №1

This unique API provides an object containing the "data" property, which can be utilized to showcase population statistics.

fetch('https://specific-api-source.com/data?drilldowns=Area&measures=Population')
  .then(function (response) {
    return response.json();
  })
  .then(function (result) {
    const populationData = result.data;
    displayData(populationData);
  })
  .catch(function (error) {
    console.log('An error occurred: ' + error);
  });

function displayData(data) {
  var container = document.getElementById('myData');
  var newDiv = document.createElement('div');
  newDiv.innerHTML = 'Location: ' + data[0].Population;
  container.appendChild(newDiv);
  
}


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

It appears that the Facebook share feature is not picking up any meta OG tags

There seems to be an issue with my Facebook share functionality as it's not reading any of the meta tags. It is indicating that the required properties such as og:url, og:type, og:title, og:image, og:description, and fb:app_id are missing. <script ...

Mocha retries causing logging malfunction: a problem to address

My current situation involves testing something on our network, and occasionally the network experiences delays causing the test to end prematurely. To address this issue, I attempted to set the test to retry with the command this.retries(1). While this ...

tips for accessing a PHP variable within an AJAX success function and setting it as a JavaScript variable

How can I access a PHP back end variable in a front-end AJAX success callback function? Here is my PHP code: if($_POST["action"] == 'check_ot_count') { $totaltime = 0; $ot_hours = $_POST["test"]; $month = $_P ...

Discovering the file extension and ensuring its validity when imported from Google Drive

I am facing an issue with a select tag that has 3 options: powerpoint, pdf, and spreadsheet. When uploading from Google Drive, there is no validation in place, so I can give a ppt link to the pdf option and it will still upload. Can someone help me with va ...

Creating a specialized serializer adapter for Gson that can be utilized in .NET: a step-by-step guide

I am currently facing an issue with serializing data between a .NET Rest webservice that returns Json responses and my Java application. I am using Gson for serialization and deserialization. The problem arises when dealing with polymorphism between the t ...

What is the best way to convert a Java 8 LocalDateTime property to a JavaScript-style Date String when using JAX-RS?

I implemented a RESTful web service using JAX-RS method annotations: @GET @Path("/test") @Produces(MediaType.APPLICATION_JSON) public MyThing test() { MyThing myObject = new MyThing(LocalDateTime.now()); return myObject; } Everything is working s ...

The content of package.json should adhere to the JSON format strictly, rather than being in

After utilizing http://jsonlint.com/ to verify the syntax of this package.json file, here's what I found: { "name": "hello-world", "description": "hello world test app", "version": "0.0.1", "private": true, "dependencies": { "express": ...

Integrate Thymeleaf properties seamlessly into JavaScript code

I am attempting to embed a property from Spring's application.properties into JavaScript. It is working properly with the following code: <h1 th:utext="${@environment.getProperty('key')}"></h1> However, it returns null with th ...

Having trouble getting my asynchronous promise to work properly

I am currently working on implementing a login server function and I am struggling to understand why the promise I'm making is not being called. My setup involves using MongoDB with Mongoose as the backend, which is connected to using User.findOne. A ...

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

Utilizing Laravel's Collection to Retrieve an Array Containing Objects

I am attempting to retrieve an array of objects with my Laravel collection by using this code snippet: /** * View a user's chat rooms. * * return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory&bsol ...

Decoding JSON data into a multidimensional array

Upon receiving data from an API, the following information is retrieved: { "isVacation":"1", "date":"25.12.2014", "occasion":"1. Christmas Day", "locations":["BW","BY","BE","BB","HB","HH","HE","MV","NI","NW","RP","SL","SN","ST","SH","T ...

Dynamically allocate a controller to an element following the Bootstrap process

I have a unique AngularJS application that is initialized manually at a specific time. Later on, I need to display an HTML element without any ng-controller assigned to it. Is there a way to dynamically add an ng-controller to this element in order for it ...

What is the best way to display a series of PHP arrays within a string using echo in a loop

Having this particular string: print_r($elements); This is the output: Array ( [1] => Array ( [1] => USA [2] => CANADA [3] => BRAZIL ) [2] => Array ( [1 ...

Creating distinctive, unchanging colors for individual ellipses within a collection in p5.js

It's clear that each ellipse is part of a wave object, with the fill color applied on every frame causing a blinking effect. I'm trying to assign a random color to each ellipse when it's drawn, so it maintains that fill color instead of chan ...

JSON Schema: Mandate a property if any nested item contains a different property

Within my dataset, I have the following structure: { "ELEMENTS": { "element_1": { "requiredPropIfAtLeastOneFlag": "", "ITEMS": { "item_1": { "flag": & ...

Angular2 and ES6 Promise in JavaScript - tackling the issue of undefined variables

I am working with an array of objects like the one shown below: let PAGES = [ new BasePage( 'home', 'test') ]; let pagesPromise = Promise.resolve(PAGES); My goal is to retrieve a BasePage object by calling the following met ...

Modify the color of a div element in React when it is clicked on

My goal is to change the color of each div individually when clicked. However, I am facing an issue where all divs change color at once when only one is clicked. I need help in modifying my code to achieve the desired behavior. Below is the current implem ...

Utilizing $.Deferred() in a loop of nested ajax requests

I have spent countless hours searching for solutions to my problem, but I am still hopeful that someone out there has a solution. The issue at hand is being able to receive a notification once function a() has finished its execution. The challenge lies in ...

The necessary set of dependencies for implementing the Jackson mapper

Recently, I started working with Jackson in my coding exercises. As I was exploring the new version of the Jackson library on Fasterxml's website: Jackson, I decided to add the following dependencies to my Maven POM-file: <dependency> <gr ...