Iterating through each object in the JSON file to showcase details about planes

Question

How do I set up a functional example of these airplanes?


Background

I seem to have the initial part working, indicating that my loop may be causing issues. While I can extract the number of planes, I'm facing difficulties displaying all the planes.

You can find my Demo on CodePen here

I've been referring to the documentation available at this link but it lacks a complete functional example. My goal is to showcase the plane name, country, and display a large image. The styling can come later, but right now, I require a functioning example to kickstart my understanding and progress.


Code

API

I am retrieving data from this API endpoint

JSON output

https://i.sstatic.net/pwcUM.png

HTML

<p>There are a total of <span id="planeQuantity"></span> planes in the database.</p> <ul id="planes"></ul>

jQuery from

Link to jQuery

Javascript

var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo"; $.getJSON(queryURL, function (data) { var quantity = data.meta.count; $('#planeQuantity').append( quantity ); var name = data.id.name_i8n; var nation = data.id.nation; var lrgImg = data.id.images.large; $(data).each(function(){ console.log($(this).id); $('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>'); }); }) 

Answer №1

I made some adjustments to your code and here are some comments:

  1. Since your data.data is an Object, you can use for (key in object) for iterating through each key (you can also use jQuery's each, but this is a JavaScript approach);

  2. The correct spelling for name_i8n should be name_i18n;

  3. All your assignments like var = name, var = nation, and var = lrgImg should go inside the loop.

Here is the final code:

var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";

$.getJSON(queryURL, function (data) {

  var quantity = data.meta.count;

  $('#planeQuantity').append( quantity );

  for (key in data.data) {

    var item = data.data[key];

    var name = item.name_i18n;
    var nation = item.nation;
    var lrgImg = item.images.large;    

    $('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');

  }
})

Working pen: http://codepen.io/mrlew/pen/vgaexb


Edited with some explanation

You received a data Object that contains a data key which holds a large Object with a structure similar to this:

{
    "7290": { /* ... */ },
    "7291": {
        "name_i18n": "North American FJ-1 Fury",
        "nation":"usa",
        "images":{
            "large":"http://worldofwarplanes....png",
            /* ... */
        },
        /* ... */
    },
    "7292": { /* ... */ }

}

To iterate over all keys of data.data, we can use for (key in data.data) { }.

During each iteration, the variable key will be assigned the object key such as 7290, 7291, 7292. To access the corresponding value, we use data.data[key] (e.g., data.data["7291"]) and assign it to the variable item.

In JavaScript, using brackets is one method to retrieve values from an Object. Another way is through dot notation, though it doesn't work with numeric keys.

Valid usage:

data["data"]["7291"]

Invalid usage:

data.data.7291

Answer №2

It is important to assign unique values to name, nation and lrgImg within the each function in order to avoid uniform elements. Additionally, make sure to iterate through the nested data object (data.data). Here's an example:

var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";

$.getJSON(queryURL, function(data) {

  var quantity = data.meta.count;

  $('#planeQuantity').append(quantity);

  $.each(data.data, function(key, value){
    var name = value.name_i18n; // extract the name
    var nation = value.nation; // extract the nation
    var lrgImg = value.images.large; // extract large image

    $('#planes').append('<li>' + name + ' hails from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
  });
});

Answer №3

let requestURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/? application_id=demo";

$.getJSON(requestURL, function (response) {
    let totalPlanes = response.meta.count;
    $('#planeCount').append( totalPlanes );

   $.each(response.data, function(index, element) {
       let planeName = element.name_i18n;
       let country = element.nation;
       let largeImage = element.images.large;

       $('#planeList').append('<li>' + planeName + ' is from ' + country + '<img src="' + largeImage + '">' + '</li>');
   });
});

Answer №4

To successfully loop through the data.data object, you should utilize $.each() instead of $.fn.each(), especially if you're not dealing with DOM elements.

$.each(data.data, function(index, item){

   console.log(index) // "4101"
   console.log(item.name) // "type=91"
})

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

I have some information stored in JSON format and I am looking to transform it into a CSV file

#include <bsoncxx/builder/stream/document.hpp> #include <bsoncxx/json.hpp> #include <mongocxx/client.hpp> #include <mongocxx/instance.hpp> #include <fstream> #include <iostream> #include <string> using namespace s ...

Guide to creating a Javascript API wrapper

I'm currently working on a React client and I have a question regarding the implementation of a JavaScript wrapper. The APIs I am using return more data than is necessary for the client, so I want to create an index.js file where I can call the API, r ...

Is there a way to ensure the collapsible item stays in its position?

I'm encountering an issue with the display of items within collapsible cards. Here is what it currently looks like: https://i.sstatic.net/DM8sX.png And this is how I want it to appear: https://i.sstatic.net/BXGpW.png Is there a way to achieve the ...

Getting URL Parameters in Angular JS

How should one go about retrieving URL parameters in Angular? For instance, consider this URL: http://example.com/mypage.html?product=1234®ion=4&lang=en Thank you ...

Navigate through the options on the left menu by sliding your

I'm attempting to create a menu that slides in a submenu from the left on hover, but the issue is that with this code, all submenus open instead of just the one related to the hovered link. Here is my HTML code: <ul id="NavMenu"> ...

The asynchronous functionality for reading and writing files from 'fs' is not functioning properly

I've been working on a script that reads and writes files, and so far the functions are functioning properly. However, I am facing challenges in making the read/write functions asynchronous. The main issue arises when trying to write a file and then i ...

Obtaining an element through its id using an expression in an Angular directive

Here's a complex question that needs to be broken down. I'm trying to mimic the behavior of the native <label> for <input>. Since nesting is not an option, I use a style like this: <input type="checkbox" id="test" /> Some other ...

Experiencing an issue where the canvas element fails to render on mobile Chrome browser,

I've encountered an issue with a script that draws a canvas based on the background color of an image. The image is loaded dynamically from a database using PHP. The responsive functionality works fine on mobile Safari, but not on Chrome. When the re ...

What could be causing app.put() to fail in updating documents within mongodb?

I am currently working on implementing a form in an ejs file where, upon clicking a button, the "likes" attribute of a displayed document from my mongoDB collection should be set to 0 using a "PUT" request. However, for some reason, the document does not u ...

NextJS is throwing an error: The prop `href` in `<Link>` should be a `string` or `object`, but it received `undefined` instead

I've encountered an issue while trying to integrate a header section from a GatsbyJS project into my NextJS project. The error message I'm receiving is: "Error: Failed prop type: The prop href expects a string or object in <Link>, but ...

tips for adding text to an input field after it has been submitted

Is there a way to automatically add text to an input field after the user has entered their information? For example, if a user types "youtube.com" into a search bar, could the input then apply ""? ...

"Unravel cyclic dependencies in Java objects using Jackson for des

I have a JSON string that looks similar to the following (simplified): [ { "id":1, "connections":[2] }, { "id":2, "connections":[1,3] }, { "id":3, "connections":[] } ] In this JSON structure, the "connections" represent the IDs of other users withi ...

What is the best way to emphasize a table row during a search rather than just the text?

I am currently using a jQuery script that searches for a specific string in a simple text input field and highlights only the string itself if it is found. However, my data is organized within a table and I am interested in knowing if it is possible to hig ...

Error: The index "id" is not defined

Hey there, I have been working on fetching data from a JSON URL located at this link. However, I seem to be encountering an error that I can't quite comprehend. If anyone has any insights or solutions, I would greatly appreciate the help. Thank you in ...

Issue: Incompatibility in metadata versions detected for module .../ngx-masonry/ngx-masonry.d.ts. Level 4 version identified, whereas level 3 version

When using ngx-masonry, I encountered the following error message- ERROR in Error: Metadata version mismatch for module .../ngx-masonry/ngx-masonry.d.ts, found version 4, expected 3 Specifications: Angular 4 ngx-masonry 1.1.4 ...

How can I utilize data retrieved from $http.get in Vue.js once the page has finished loading?

I'm having trouble figuring out how to trigger a function in Vue.js after an $http.get request has completed. In the example below, I want to automatically select an element of foobar right after the page loads, but it only works when there's an ...

I need assistance with an issue on my Google Dev Console, as it keeps showing an error stating that ".getcontext is

Looking for some assistance here as my development console keeps displaying an error: Uncaught TypeError: canvas.getContext is not a function. Here is the problematic code snippet: `var canvas = document.createElement; var c = canvas.getContext("2d&qu ...

An error message stating "ReferenceError: str is not defined" was encountered in Firefox while using the Gettext Library

The gettext.js library seems to be giving me trouble. When I try to run the "index.html" file, an error message saying "ReferenceError: str is not defined" pops up. this.LCmessages[lang] = new jsGettext.Parse(str); I'm not sure where the str variabl ...

Generating variables dynamically within a React Native component

In my React Native component, I need to create a variable that will be used multiple times. Each instance of this component should have a different variable name for reference. <View ref={view => { shapeView = view; }} onLayout={({ nativeE ...

ensure that angular's ng-if directive sets aside space to display content when triggered by an event

I'm facing an issue with my modal form setup where if a text-field is left blank, a label saying "it is required" is generated below the field, causing the "Proceed" button to move (along with all other elements below it). How can I make sure that DOM ...