Encountered an issue while trying to retrieve a value from an object within a

Reviewing the following JSON response:

 [
   {"name": "Afghanistan", ...},
   {"name": "country 2" ,...},
   {"name": "country 3" ,...},       
  ]

My goal is to extract only country names from the array. Can someone advise me on how I can achieve this?

async function fetchData(data, name) {
  var x = await fetch("https://restcountries.eu/rest/v2/all");
  var data = await x.json();
  
  var countryNames = [];
  for (let i = 0; i <= data.length; i++) {
    var countryName = data[i].name;
    
    countryNames.push(countryName)
  }
  console.log(countryNames);
}

fetchData();

Answer №1

If you're looking to manipulate an array in JavaScript, consider using Array.prototype.map(). This method loops through each element and allows you to create a new array based on the original.

const response = [{"name": "Afghanistan",},{"name": "country 2",},{"name": "country 3",}]

// Extracting country names from the response array
const countryNames = response.map(country => country.name)
console.log(countryNames)

In case of data inconsistencies in the response object, there's an alternative approach that uses Array.prototype.flatMap(), which combines mapping and flattening operations to handle potential undefined values more gracefully.

const response = [{"name": "Afghanistan",},{"name": "country 2",},{"name": "country 3",},{"something": "with no name"}]

// Extracting country names or handling undefined values
const countryNames = response.flatMap(country => country.name || [])
console.log(countryNames)

Answer №2

The issue lies in the for loop condition, which currently reads as

for (let i = 0; i < data.length; i++)

async function fetchValues(data, name) {
  var response = await fetch("https://restcountries.eu/rest/v2/all");
  var jsonData = await response.json();
  
  var countryNames = [];
  for (let index = 0; index < jsonData.length; index++) {
    var countryName = jsonData[index].name;
    
    countryNames.push(countryName);
  }
  console.log(countryNames);  // This line should be inside the for loop to display correct output
}

fetchValues();

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

Add and condense sub-row

I am struggling to make the child row collapse and append when clicking on the parent row. It seems like my code is not working properly. Can anyone offer some guidance or assistance? This is the code for the parent row: $j(document).ready(function(){ $ ...

Can I inform the interpreter that my function in TypeScript specifically handles undefined and null values?

Consider a scenario where there is a method isEmpty that verifies if a value is empty, null, or undefined, and returns true accordingly. In TypeScript, this method may not effectively communicate to the interpreter, leading to a red underline in IDEs like ...

Retrieve the text and image simultaneously using jQuery

I need to retrieve either text or image within a modal. Use textCont to retrieve text. The content within a div can be either text or image. It will retrieve whatever is present there. Below is the JavaScript code for text retrieval. var contId = 0; var ...

Retrieve JSON data from PHP using D3.request

Looking to extract data from an SQL database using PHP and then convert it into JSON format with the "echo json_encode($array);" function. I have a requirement to create a graph using D3.js, which means I need to transfer this JSON data from PHP. Can anyo ...

Explore the inner workings of Perl's JSON structure

Obtaining the JSON data from a request: use HTTP::Tiny; my $response = HTTP::Tiny->new->get('https://jsonplaceholder.typicode.com/todos/1'); print "-------------------**------------------- \n"; my $content = $response->{content}; ...

Getting the URL for a downloaded image using ImageLoad on Android

I encountered an issue with my Android application In the database, I stored URLs of some images and now want to download these images for a viewpager display using ImageLoader. The problem arises when trying to download the image URLs from the server. I ...

Error alert: Unable to find the specified word

Having trouble writing a word to the database due to an error: ReferenceError: Patikrinta is not defined. Below is my ajax script for sending data to a PHP file, and then the PHP script itself if needed. Haven't found a solution on Stack Overflow. $s ...

Utilizing JQuery to Retrieve JSONP Data from WCF

Lately, I've been encountering difficulties with fetching JSON data from a WCF service application that I developed. The WCF service is pretty straightforward and returns the following JSON results: [{"RoomId":1,"RoomName":"Big Room"},{"RoomId":2,"Ro ...

The invocation of `prisma.profile.findUnique()` is invalid due to inconsistent column data. An invalid character 'u' was found at index 0, resulting in a malformed ObjectID

The project I'm working on is built using Next.js with Prisma and MongoDB integration. Below is the content of my Prisma schema file: generator client { provider = "prisma-client-js" } datasource db { provider = "mongodb" url = env("DATABA ...

What is the best way to adjust text across several lines to perfectly fit within a div's width?

http://codepen.io/anon/pen/oXGMQZ Is there a way to automatically adjust the font size of each span within a parent div so that it fills the width of the parent div? <div class="box"> <span class="fit">what</span> <span class="fi ...

Dealing with Unicode characters in Java and storing the output in both MySQL and HBase databases

In my possession is a massive Twitter dataset containing tweets stored as JSON objects. Each tweet includes a field for the tweet text, which consists of a sequence of Unicode characters. The challenge I face is storing this tweet text in both MySql and HB ...

Serializing Handpicked Attributes from an Array of Objects

When working in C#, I have a collection class called FeatureCollection that I need to serialize into JSON and send back to the caller. The issue is that the Feature class has 5 properties, but the caller only requires 2 of them. To optimize response time, ...

The connection between MongoClient and Express has been established successfully, however, an error occcurred: TypeError: Cannot read the property 'collection' of null

I am currently working with the MongoClient instead of mongoose, but I am facing an issue where I can't seem to set a new collection in my routes file. db/index.js const {MongoClient} = require('mongodb'); const MONGO_DB_NAME = 'mooo ...

Issue with this.setState() not updating value despite not being related to asynchronous updates

Just a quick note, this specific question does not involve any asynchronous update problem (at least, as far as I can tell). I currently have a class component with the following code snippet (simplified for clarity on the main issue): constructor(props ...

Changing position of element upon appearance of span in React

Currently, I am working with React and facing an issue where a span element appears whenever a user hovers over a text element. The problem is that the existing text shifts leftwards when the span appears (to the right of the text). The desired behavior ...

Issue: app.database function is not recognized with Firebase

I'm attempting to integrate Firebase realtime database into my Vue application, but I keep encountering the following error: TypeError: app.database is not a function This is what my code looks like: File: Firebase.js var firebase = require(' ...

Instructions for creating a JavaScript click function that iterates through all records, not just the initial record

Although I'm new to web development and still learning the basics of html, javascript, etc., I have a problem that seems quite simple. The challenge lies in understanding javascript functions, which I find particularly tough to grasp. Here's what ...

Is there a way to change the format of the date "Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time)" to JAN 01, 2020 in JavaScript?

I am currently retrieving the date from the database in the format of Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time), but I would like it to be displayed in the JAN O1,2020 format without using moment.js. Is there any alternative approach to ach ...

What's the reason behind my REST API delivering a 401 error code?

New Update After being encouraged to implement debug logs, I have discovered that the issue lies with Spring reporting an invalid CSRF token for the notices controller. I have compared the headers generated by Postman and the fetch requests, but found no ...

Using a Typescript variable prior to its assignment

I encountered an issue in my Typescript / ReactJS project displaying the error message Variable 'myVar' is used before being assigned. TS2454 This problem arises with my TS version 4.2.3, appearing both in my IDE and during code execution. Inte ...