Difficulty navigating through nested arrays

One instance involves the use of the fetch API to retrieve data from the NY Times API. Within the response, there is an object titled "Multimedia" containing images. I've devised a template literal to extract the required information but for some reason, the images are not loading properly. VIEW DEMO ON CODEPEN Below is my code:

const div = document.getElementById('article'),
      url = "https://api.nytimes.com/svc/topstories/v2/home.json?api-key=fd168d666e644fe29bbb534d757b374e";

fetch(url)
.then((response) => {return response.json(); })
.then(data => {  
  
  let article = data.results;
  console.log(article);

  return article.map(user => {
    let output = '<div class="container">';
    article.forEach(user => {
      output += `
      <article>
        <img src="${user.multimedia.url}">
        <h2>${user.title}</h2>
        <span class="author"><b>Author:</b> ${user.byline} | <b>Category: </b>${user.section}</span>
        <p>${user.abstract}</p>
        <a class="btn" href="${user.url}" target="_blank">View Article</a>
      </article>
    `
    });
    document.getElementById('article').innerHTML = output;
  })
})
.catch( error => { console.log(error); })
 
%body
  #article

I have attempted to access the images using user.multimedia.url but unfortunately, they are not displaying. Any assistance or insight into why this issue persists would be greatly appreciated. Thank you!

Answer №2

To properly loop through the user.multimedia array, you can use the following code snippet:

var images = "";
    articles.forEach(user => {
      user.multimedia.forEach(img=>{
       images += "<img src="+img.url+">"
      })

Then, include ${images} in the output where you want to display the images. Since there are multiple images available in different sizes, make sure to select the appropriate size for display.

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

When updating an object, JsonConvert PopulateObject does not populate null values for nullable integers

I am currently working on updating a user object Below is the structure of my model: public class User:BaseModel { [Display(Name="E-Posta"),Required(ErrorMessage ="Kullanıcı adı (Email) Zorunludur")] [JsonProperty(NullValueH ...

Transforming an array in JavaScript into a JSON object

I'm currently working on creating a loop in JavaScript or jQuery to generate a new JSON object from an array. The goal is to convert an input JavaScript array into a desired format for the output. Here's the input array: INPUT: [ { ...

retrieve information in json format from a specified web address

I need to figure out why the data from a specific URL is not being displayed properly on my node application. It seems like there might be an error in my code. const extractRefDefaultSchema = async (data) => { const url = "https://mos.esante.gouv.f ...

Using Nuxtjs/Toast with personalized image emblems

Would it be possible to include an icon in a toast error message, or is there a need to install another module for this functionality? I am currently using vue and attempting to integrate a component as an icon, but so far without success. this.$toast.er ...

JavaScript code returning the correct result, however, it is unable to capture all characters in the returned string

Currently, I am utilizing $.post to retrieve results from a database. The syntax I am using is as follows: $.post('addbundle_summary', {id:id}, function(resultsummary) { alert(resultsummary[0]); }) In CodeIgniter, within my model, I am retu ...

Having issues with Angular Material, specifically with mat-list-item and routerLinkActive not functioning as expected

Currently, I am working with a navigation view that utilizes the MatSidenavModule. The issue I am encountering is on mobile screens. When I click a mat-list-item, the mat-sidenav closes as expected. However, upon opening the mat-sidenav again, Material alw ...

Switching code from using .hover() to using .click() while still maintaining the functionality of both.orChanging code to switch

How can I change this script to trigger on click and also maintain the hover functionality: $x = jQuery.noConflict(); $x(document).ready(function () { $x(".swatch-anchor").on('click hover', function () { var newTitle = $x(this).attr( ...

Using Javascript to save basic high scores to a server

My JS game involves updating a score variable. When the game reaches a gameOver state, I want to compare the score to one saved on the server. If the player got a higher score, I'd like to overwrite the previous high score with the new one. If it&apos ...

What could be causing this conflicting behavior with the logical "and" operator?

const {DEMO, PORT, LOCAL} = process.env; const socketAddress = (DEMO & LOCAL)? `http://${hostname}:${PORT}`: `wss://${hostname}`; When DEMO is false, PORT is undefined, and LOCAL is true The hostname being used is http://9f9cbf19.ngrok.io I verified ...

Error: The property 'price' is not defined and cannot be read

As I work on setting up my online store for teaching node.js, I encountered an issue when trying to delete a product from the products.json file. Surprisingly, once a product is removed, the corresponding entry in cart.json gets deleted as well. The error ...

Uploading files using Remix.run: Transforming a File object into a string during the action

I'm currently developing a Remix application that allows users to upload files through a form. I have a handler function for handling the form submission, which takes all the form data, including file attachments, and sends it to my action. The probl ...

Tips for dynamically changing the class of a form field in jQuery when it is empty

I am currently working on a form that looks like this; <form id="myform" name="myform"> <input type="text" class="required" value="" name="qwer" /><br /> <input type="text" value="" name="asdf" /><br /> <input type=" ...

Is it the correct method to query names within JavaScript arrays?

I am looking to create a dynamic list view using React JS without relying on any pre-built components. My goal is to incorporate a basic search function that can find users by their names, and I need to address this issue... For example, I have drafted th ...

Adding a JavaScript variable into a Django template tag

This particular situation has been presenting a challenge for me. So far, I have been using query parameters instead of a variable within the {% url %} tag. However, I can't help but wonder if there is a way to achieve this: I am interested in includ ...

What is the best way to integrate node.js with HTML?

I am currently utilizing node.js to interact with an API on the IBM Cloud platform. I have successfully accessed the response in my code, but now I need to pass this data to an HTML page using "res.send". How can I achieve this? Below is the Node.js code ...

In JavaScript, how is the symbol "." referred to as?

While I am familiar with its purpose and the language terminology, could you please provide the official name for the period/dot used in Javascript/jQuery? Appreciate your help! ...

Dropzone is encountering an issue with uploading photos: The upload path seems to be invalid

Despite thoroughly checking the path settings in my code, the error message persists when I attempt to upload photos using Dropzone. It seems to be indicating a problem with the upload path. What could be causing this issue? I am currently in the process ...

Using ng-class in Angular.js with a boolean retrieved from a service: A step-by-step guide

I need to dynamically set a class based on a boolean value that is determined in a service. This example is simplified for readability, but in reality, the boolean would be set by multiple functions within the service. Here is how it would look in HTML: ...

Determine the HTTP request method when capturing AJAX responses

As I take control of all AJAX responses on a global scale, I find myself searching for an elegant solution to identify the method (such as POST/PUT/GET) that was initially used to make the request triggering the intercepted response. Below is my approach ...

Utilizing Flutter and Dart to efficiently convert JSON time series data into a map structure containing key-value pairs

Encountered a message regarding "anonymous closure" in the TimeSeriesAdjusted.fromJson method, indicating a subtype error that I'm having trouble identifying. [VERBOSE-2:ui_dart_state.cc(199)] Unhandled Exception: type 'Null' is not a subtyp ...