Tips for showcasing nested information on the web page

Attempting to retrieve data from an API and insert it into the DOM

In this case, the data is in the form of an array containing objects.

Here's a sample of what the API displays in the console.

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

To access the array within the object, I am utilizing both a for loop and a for...in loop

Check out the code snippet below

const getNews = document.getElementById('btn')

heyThere = () => {
    axios.get('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=APIKEY')
        .then(function (response) {
            for (let i = 0; i <= response.data.articles.length; i++) {
                for (key in response.data.articles[i]) {
                    ham.innerHTML = (response.data.articles)
                }
            }
            console.log(response)
            console.log(typeof response)
        })
        .catch(function (error) {
            console.log(error);
        })
}

getNews.addEventListener('click', heyThere)

The code above will display the following on the DOM

https://i.sstatic.net/7zSBi.png

What is the appropriate method to access the entire list of articles (20 articles) and showcase them on the DOM?

Answer №1

To effectively display the specific properties of response.data.articles[i], you must access and manipulate them in order to generate the desired HTML content for each one. A potential approach could be as follows:

const fetchNews = document.getElementById('btn')

fetchData = () => {
  axios.get('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=APIKEY')
    .then(function(response) {
      let htmlContent = '';
      response.data.articles.forEach(article => {
        htmlContent += '<div class="article">';
        htmlContent += `<div class="author">${article.author}</div>`;
        htmlContent += `<div class="description">${article.description}</div>`;
        htmlContent += '</div>';
      });
      getNews.innerHTML = htmlContent;
      console.log(response)
      console.log(typeof response)
    })
    .catch(function(error) {
      console.log(error);
    })
}

fetchNews.addEventListener('click', fetchData)

Answer №2

The solution provided demonstrates how to display articles on the webpage as a list.

displayArticles = () => {
    axios.get('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=APIKEY')
        .then(function (response) {
            let news = response.data.articles
            for (let i = 0, len = news.length; i < len; i++) {
                console.log(news[i])
                let li = document.createElement('li')
                li.innerHTML = JSON.stringify(news[i].title)
                document.querySelector('#ham').appendChild(li)
            }
        })
        .catch(function (error) {
            console.log(error);
        })
}

getNews.addEventListener('click', displayArticles)

Displayed below are the articles that have been added to the page.

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

To retrieve specific information like URLs or authors, you can use dot notation on the response object. For example,

li.innerHTML = JSON.stringify(news[i].url)
.

We hope this explanation proves useful!

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

Rotating an object in Three.js along the radius of a sphere

I want to position an object at the end of a sphere's radius based on its coordinates (x, y, z). In traditional mathematical formulas for the coordinates of a point on a sphere, we use: var x = radius * Math.cos(phi) * Math.cos(theta); var y = radiu ...

Selecting a range with regular expressions

I'm having trouble extracting a specific key-value pair from a JSON document using regular expressions. I'm finding it hard to figure out how to narrow down the selection of the matching data. Currently, when using the following regex, "email"& ...

Completely different method for transmitting an array to NodeJS through AJAX

Recently, I've encountered difficulties when sending arrays to NodeJS using AJAX. It seems that whenever I try to send it with JSON, the error function is always triggered. Despite seeking explanations, I haven't found a satisfactory answer. The ...

Integrate several YouTube players within a tabbed angular-ui system. Looking to incorporate a collapse feature

I come to you with a humble request for guidance. As a newcomer to Angular and someone who has never ventured into the realm of the YouTube JavaScript API, I am well aware that I may be making errors without even realizing it. While my code appears to be f ...

What is the process for removing a specific photo from a user's profile if the photo in question has a file beginning with file://?

How can I delete a specific photo object of the user if that photo object starts with file://? I am currently working on adding an image feature in my app using NodeJs. The route I have created for uploading images is functioning properly. However, I encou ...

What is the best method for retrieving JSON POST data in ASP.NET Web Forms?

I have implemented some jquery code on my website to post data. Currently, I am testing the code by posting JSON data. However, I am facing difficulties in retrieving the data on the back-end once it has been posted. Typically, I have used Request.Params ...

Ways to update HTML content generated by Ajax

Having some difficulties modifying the HTML content generated by AJAX. This is the code snippet from the page: @model IEnumerable<WE_SRW_PeerNissen.Models.Reservations> @{ ViewBag.Title = "List"; Layout = "~/Views/Shared/_Layout.cshtml"; } ...

Determine the data type of a string without needing to convert it

Can you determine if a value is numeric without casting it? For example, how can you differentiate between 'abc' and '123' without converting them to a specific data type? While visually apparent that 'abc' is not numeric, t ...

Implementing pagination using getServerSideProps in NextJS allows for dynamic

I'm currently using NextJS along with Supabase for my database needs. I'm facing a challenge with implementing pagination as the solution I'm seeking involves passing queries to the API. However, since I'm fetching data directly from th ...

Jackson Library - com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException

Upon attempting to deserialize the Automobile class, I encounter an error where Jackson is searching for a field in the child element within the parent class. How can I ensure that Jackson uses the appropriate child type for deserialization? It seems like ...

Is it possible to utilize the Zoho Inventory API to enable tracking of both inventory and serial numbers for items?

I'm currently utilizing the Zoho Inventory API to modify an item, but it appears that the inventory tracking details are not being reflected in the API. Any suggestions for a workaround, or do I simply have to wait for V2 of the API? https://i.sstati ...

How to dynamically update the maximum y-axis value in Vue-Chart.js without having to completely re-render the entire

Currently, I am involved in a project that requires the implementation of various charts from the Vue-Chartjs library. One specific requirement is to dynamically change the maximum value on the Y-axis whenever users apply different filters. To achieve this ...

Unlock a multitude of outcomes with Sequelize

Is there a way to retrieve multiple results from Sequelize and store them in an array? For example, I want to fetch all the values in the name field from the test table and display them in the console. This is what I tried: test.findAll().them(function(re ...

Retrieve all rows in Excel array that do not contain errors

Table 1, located in the range D1:F20, contains various data where some rows have #N/A in column D. The headers for this table are in cells D1:F1. To address this issue, I am looking to create Table 2, which will gather all data from Table 1 except those w ...

Passing object attributes to a modal in AngularJS

I am trying to figure out how to pass a complete object to my modal so that I can view all of its attributes there. Currently, the items I have look like this: $scope.items = [{ Title: title, Id: id }] On my html page, I am using 'ng-repeat' as ...

How can I show the initial three digits and last three digits when using ngFor loop in Angular?

Greetings! I have a list of numbers as shown below: array = [1,2,3,4,5,6,7,8,9,10] By using *ngFor, I am displaying the numbers like this: <div *ngFor =" let data of array"> <p>{{data}}</p> </div> Now, instead of d ...

Enhancing next-auth and i18n functionality with middleware in the latest version of next.js (13) using the app

Currently, I have successfully set up next-auth in my next.js 13 project with app router, and it is functioning as expected. My next step is to incorporate internationalization into my app following the guidelines provided in the next.js documentation. How ...

Pass data from JavaScript to PHP using AJAX

Using Leaflet to display a map, I have incorporated ajax into my onEachFeature function in order to retrieve variables to pass to PHP. Here is the code snippet: function onEachFeature(feature, layer) { layer.bindPopup(feature.properties.IDLo); layer. ...

Component is unable to access global styles

Component utilizing global styles Global styles are specific to this component only, such as col-lg-2, col-md-4 -> global style import React from 'react' import ReactDOM from 'react-dom' import { AppContainer } from 'react-hot ...

Vertical alignment of content over image is not in sync

I am attempting to center my div container .home-img-text vertically in the middle of its parent div .home-img. Despite trying various methods such as setting .home-img-text to position: absolute, relative, adding padding-top, and several others, I haven&a ...