What is the method for accessing an element in an object?

I am attempting to access a specific element of an object from an API endpoint () - in this case, the "name" from the "currencies" property. However, each time I try to do so, it returns undefined.

I have experimented with both currencies.name and currencies["name"], but neither seems to be effective.

const countries = document.getElementById('countries');

var request = new XMLHttpRequest();

request.open('GET', 'https://restcountries.eu/rest/v2/all', true);

data.forEach(name => {
        const h1 = document.createElement('h1');
        h1.textContent = name.capital; //this function works properly

        const h2 = document.createElement('h2');
        h2.textContent = name.currencies.name; //the issue lies here

        countries.appendChild(h1);
        countries.appendChild(h2);
 });

The desired outcome is to retrieve something like "Afghan afghani", rather than encountering the previous undefined result.

Answer №1

The issue at hand is that the variable currencies is an array.

https://i.sstatic.net/6sRgb.png

To solve this problem, you need to access the currency names using name.currencies[0].name. If there are multiple currencies, you will need to loop through the array to retrieve all of them.

Answer №2

One issue lies in the fact that 'currencies' is an array.

To retrieve the name of the first currency, utilize currencies[0].name.

Answer №3

If you're looking to display a list of countries along with their respective currencies, you can achieve this easily without worrying about different currencies per country:

const countriesList = document.getElementById('countries');
const request = new XMLHttpRequest();

request.open('GET', 'https://restcountries.eu/rest/v2/all', true);

request.onload = function (e) {
  if (request.readyState === 4) {
    if (request.status === 200) {

      const data = JSON.parse(request.responseText);

      data.forEach(function(country){

        // Add country name
        const heading1 = document.createElement('h1');
        heading1.textContent = country.name; 
        countriesList.appendChild(heading1);

        // List the country's currencies
        country.currencies.forEach(function(currency){
          const heading2 = document.createElement('h2');
          heading2.textContent = currency.name; 
          countriesList.appendChild(heading2);
        });

      });  

    } else {
      console.error(request.statusText);
    }
  }
};

request.onerror = function (e) {
  console.error(request.statusText);
};

request.send(null);

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

How can I retrieve the width of HTML content without referring to the width of the window?

Is there a way to determine the total width of the HTML content, including what is visible and what is hidden due to vertical scrolling when the window size is reduced and a scrollbar appears? ...

Pressing a button meant to transfer text from a textarea results in the typed content failing to show up

Having trouble with a custom text area called a math field. I'm currently interning on a project to build a math search engine, where users can input plain text and LaTeX equations into a query bar. The issue I'm facing is that sometimes when th ...

The jQuery mobile button may occasionally appear selected without triggering a page transition

When using a Phonegap Application with jQuery mobile, I have encountered an issue where clicking a button sometimes only selects it and does not transition to the next page. This even happens with the back buttons generated automatically by the library, re ...

Managing individual HTTP responses within Angular 6

I currently have 15 HTTP requests being sent to the API individually. Instead of waiting for all requests to finish processing (especially one that can take a few minutes), I want to handle responses as they come in. On the service side: findOneByOne ...

Redux repeatedly triggers re-rendering despite the absence of any changes in the state

This is my first venture into React-Redux projects. I was under the impression that React only re-renders when a component's state changes. However, I am currently facing confusion. The component is being re-rendered every 1 to 3 seconds even thoug ...

What is the best way to manage json-parse errors in a node.js environment?

After countless hours of research, I am still unable to find a solution to my seemingly simple and common problem: In Node.js using Express, I want to retrieve JSON-data via http-POST. To simplify the process, I intend to utilize the app.use(express.json( ...

Use PHP's post function in combination with the JSON_ENCODE method for

I am currently working on developing the backend for my application, which needs to support sending emoticons. The issue arises when using a form with php POST to send the data to a file that will then trigger a notification containing the emoticon (and op ...

Display identical text using JavaScript filter

My search filter highlight is currently displaying [object Object] instead of <mark>match values</mark> when replacing the values. This is the code I am using: this.countries.response.filter((val) => { const position = val.value.toLowerCa ...

Is there a way to remove the highlight from a non-active block?

Hey friends, I need some help with my code. Currently, when I click on a table it gets highlighted, and if I click on another table, the previous one remains highlighted along with the new one I clicked on. How can I modify the code so that when I click on ...

The three.js JSON model is rendering larger than expected on the screen

I'm currently working with three.js and I've successfully loaded a JSON file from clara.io into THREE.js. However, the 3D model is too large for my screen. Is there a way to reduce its size when loading it onto the screen? <!DOCTYPE html> ...

Regular expression designed to replace and deactivate href hyperlinks

I am looking to disable any link tags containing the href attribute that starts with "log.html" in my HTML table. My current attempt involves using string replacement. The code line I have is similar to this: str.replace(/log.html...../g,''), wh ...

Tips for maintaining selected text while a modal window is active

So I'm currently working on a document writer and I'm utilizing document.execCommand to insert links. What I aim for is the ability for a user to select/highlight text, click a button to add a link to that specific text (via a modal), and then ha ...

What is the best method to extract pictures from "Google Images" by utilizing the custom search API when the control panel restricts users to inputting only website URLs for searching?

I have been attempting to utilize the Google Custom Search API in order to retrieve images, but unfortunately I am not seeing the same results as those displayed in Google Images. When I access the custom search control panel, it instructs me to add specif ...

Struggling with PHP Strings, any solutions?

I run a website that pulls prices from the Steam Market using the item's name. My JavaScript bot then gathers information about the item and processes it to MySQL (with a PHP file handling it in another table). However, I've encountered an issue ...

How to Trigger a Modal Dialog from the Parent Component in VUE

I have been trying to toggle my modal dialog from the parent component using the steps mentioned in a related Stack Overflow Question. However, I am facing an issue where my modal dialog is not visible and appears to have an undefined value when checked in ...

Extracting JSON data from a response and setting it to state in a

I am working with an API that sends me a JSON and I need to update my state with its data. However, some variable names are different. Is there a way to update all of them at once instead of separately? The JSON data from the API request: { "name& ...

utilizing staggered animations with three.js

I am trying to animate an array of meshes in Three.js, but the properties are not being recognized. tl.staggerFrom(array, 2, {"position.y":-100}) The position.y doesn't change. When I use console.log(array[0].position.y), it gives me the initial val ...

Accessing data from an API and showcasing information on a chart using Angular

I'm currently developing a dashboard application that requires me to showcase statistics and data extracted from my MongoDB in various types of charts and maps using Angular and Spring Boot. The issue I'm facing is that when attempting to consume ...

Injecting Firebug into Firefox to interact with Pagemethods in webservices

During my work on web applications, I found it most effective to utilize a web service for server interaction while handling the rest client-side using JQuery. However, as I was testing my code, I discovered a significant vulnerability that I am unsure how ...

Issue encountered: No element found error when debugging PHP AJAX with Firebug

Hey guys, I'm running into an issue with this script where I keep getting a "no element found" error in Firebug, even after including "header('Content-Type: text/plain');". Any ideas on how to fix this? Thanks in advance. categories.php ...