Navigating through various arrays within objects on a JSON API with JavaScript: A walkthrough

I am currently working on fetching and displaying data from an API. The specific data I am interested in is located within the 'equipments' array. You can see an example of this array in the image linked below:

https://i.sstatic.net/QeBhc.jpg

My challenge lies in looping through the 'equipments' array for each item and properly displaying the data. I suspect that I may not be accessing it correctly or that I am missing an additional loop somewhere in my code.

Here is the code snippet that I have been working on:

// Fetch Data
function getData() {
  fetch(url)
    .then((res) => res.json())
    .then((data) => {
      let output = "";
      data.groups.equipments.forEach(function(product) {
        output += `
          <div class="card">
            <img src=${product.photos.text} alt=${product.model} />
            <h3>${product.year} ${product.manufacturer} ${product.model}</h3>
            <p>${product.hours} hours</p>
            <a href='https://used.battlefieldequipment.ca/en/${product["group-code"]}/${product.equipments["serial-number"]}' class="btn btn-primary">View Details</a>
          </div>         
      `;
      });
      dataOutput.innerHTML = output;
    })
}

getData();

Does anyone have any suggestions on how I can troubleshoot and resolve this issue?

Answer №1

To access the equipments within the data.groups array, make sure to iterate through each group first.

An easy way to accomplish this is by using the forEach method.

data.groups.forEach(function(group) {
  group.equipments.forEach(product) {
    output += `
          <div class="card">
            <img src=${product.photos.text} alt=${product.model} />
            <h3>${product.year} ${product.manufacturer} ${product.model}</h3>
            <p>${product.hours} hours</p>
            <a href='https://used.battlefieldequipment.ca/en/${product["group-code"]}/${product.equipments["serial-number"]}' class="btn btn-primary">View Details</a>
          </div>`;
  }
})

Answer №2

Try switching from using groups.equipments to

groups.map((g) => g.equipments)

Answer №3

To access the equipments property of the array, you need to retrieve it from an object within the array.

data.groups.forEach(item => {
  //item.equipments will give you the equipments property of the current object in the loop
})

Answer №4

To properly iterate through the data groups, you will need to use nested forEach loops. You can see an example of this in action by visiting this link.

Remember, the data groups are stored in an array, so you will need to iterate through each group and then iterate through each product in the equipment list.

Answer №5

 const fetchData = async () => {
    let apiUrl = await fetch(apiUrl)
    let response = await apiUrl.json();

    for (const group of response.groups) {
        for (const equipment of group.equipments) {
            displayProducts(equipment);
        }
    }
}; fetchData();

const displayProducts = (data) => {
    let displayElement = document.getElementById('display');
    displayElement.innerHTML = `
        <div id="product">
            <img src=${data.photos[0].text} alt=${data.model} />
            <h3>${data.year} ${data.manufacturer} ${data.model}</h3>
            <p>${data.hours} hours</p>
        </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

The URL in an AJAX request includes a repeating fragment due to a variable being passed within it

const templatePath = envVars.rootTemplateFolder + $(this).attr('link'); console.log("templatePath : ", templatePath); $.ajax({ method: "GET", url: templatePath, context: this, success : function(result){ ...

The confusion surrounding navigation in Angular's single-page applications

I'm struggling to grasp how Angular handles routing in my single-page application. Here's my issue: When I type in the url: localhost:3000/streams/ I expect the 'streams' page to load. My understanding was this: My express serve ...

JQuery addClass function not functioning properly when used in conjunction with an AJAX request

I have a website where I've implemented an AJAX pagination system. Additionally, I've included a JQUERY call to add a class to certain list items within my document ready function. $(document).ready(function(){ $(".products ul li:nth-child(3 ...

Tips on utilizing jQuery or JavaScript to efficiently filter out outcomes exceeding a specified range

<input type="range" name="rangeInput" min="100000" max="750000" onchange="updateTextInput(this.value);"> Displayed above is the slider code that provides a value output below. <div id="sliderValue"> <p>Max Value £</p> <input t ...

Function for querying database is not executing in an asynchronous manner

After setting up a function in my node server to handle querying the database and returning results, I found that using async await could help streamline the process throughout my routes. This way, I wouldn't end up with nested queries within one anot ...

Using the symbols '&', '>', and '*' in the styling of React components

Below is the code snippet in question: const useStyles = makeStyles(theme => ({ row: { '& > *': { fontSize: 12, fontWeight: 'bold', color: 'rgba(33,34,34,0.5)', letterSpacing: 0.5, ...

Guide for creating a CORS proxy server that can handle HTTPS requests with HTTP basic authentication

For my http requests, I've been utilizing a CORS-Proxy which works well for me. However, I recently stumbled upon an API for sending emails which requires http basic authentication for https requests. I'm uncertain of how to go about implementing ...

Improve the way you manage return statements

Here is the function in question: const checkifHaveBomb = (column, row) => { let isBomb = false activeBombContainer.forEach(element => { if (element.column === column && element.row === row) { ...

Unable to dial phone numbers when clicking 'Click to call' link on Android devices

Within my Cordova android application, I have a link set up like this: <a href = "tel:011123456789">Click to Call</a> While this click-to-call functionality works smoothly in IOS, it seems to be hindered in Android by an issue such as: 11- ...

The table fails to refresh after adding, modifying, or removing a row

Incorporating ReactJs with Material-UI, I am working on displaying a table of Car components where the display does not update after any Create, Edit, or Delete action has been performed. Below is the structure: class MainCar extends React.Component { c ...

Vue - Pull out several components from main file

In my Vue.js project, I have been using the .vue component specs format to write components. An interesting observation I made is that plain JavaScript can export these components when loaded from vue files. For instance, a component defined in index.vue c ...

Generating dynamic links in HTML

I've been stuck on this problem for a while now. What I'm trying to do is create a Django website that pulls in Twitch livestreams and displays them on different pages. It's a project I'm working on to learn how to use APIs in web appli ...

Stylus mistakenly fetches styl files from an incorrect directory

My issue involves a file named mobile.styl, which gathers all necessary styl files using the @import function: @import '../../common/styles/colors' @import '../../common/styles/init' @import 'landing' @import 'faq&apos ...

Is there a way to execute two files concurrently in JavaScript using node.js?

I'm a beginner in the world of Javascript and Node.js, and I've encountered some issues while trying to test code I recently wrote. Specifically, I am attempting to test the code within a file named "compareCrowe.js" using another file named "tes ...

React ES6 SystemJS encountered an unforeseen token error that couldn't be caught

Even though I have imported react and react-dom using the System.config setup below, I am still encountering the error mentioned here: Uncaught (in promise) Error: Unexpected token <(…) Here is the HTML structure: <!DOCTYPE html> <html l ...

What is the best way to extract a single image from JSON data using AngularJS?

Using ng-repeat in HTML, how can I display only a single image instead of all images? <img class="size" ng-src="{{image.image}}" /> In CSS, I aim to define the size of the image. .size { margin-left:0.3em; width:11em; height:11em; border:0.4em sol ...

Unable to edit the current value of an input component in ReactJS

I need to implement a search feature for a list of items using ReactJS. You can view the project on JSBIN. The issue I am facing is that when I input 'mi' in the search box to filter by ID, the filtration works correctly but the input value does ...

What method can be used to incorporate expressions into Handlebars partials when dealing with parameters?

Is it possible to include expressions in partials parameters? I am trying to achieve something similar to this: {{> myPartial greeting=(i18n.greeting + "my text") }} ...

Exploring the applications of the `this` keyword within a jQuery-based JavaScript object

Recently, there has been a challenge in creating a JavaScript object with the specific structure outlined below: function colorDiv(div){ this.div=div; this.div.bind("click",this.changeColor) this.changeColor(){ this.div.css(" ...

Verify the operation within a pop-up box using ruby watir

Is it possible to confirm a modal dialog window in Internet Explorer using Ruby Watir? Here is the JavaScript code for the modal dialog: jQuery('#yt100').on('click', function(){return confirm('modal dialog window text');}); ...