Skip to content
Advertisement

How to get a property value from an array of objects in JavaScript

I want to make an array with country names from a JSON file which contains an array of objects. These objects have a property name with the name of the country, which is what I need.

This is my JavaScript code which returns a list of undefined instead of country names:

import axios from 'axios';

const getTeamsFromUrl = async() => {
    const url = 'https://gist.githubusercontent.com/keeguon/2310008/raw/bdc2ce1c1e3f28f9cab5b4393c7549f38361be4e/countries.json';
    const response = await axios.get(url);
    const listOfCountries = response.data;

    // this console.log prints properly the array of objects
    // console.log(listOfCountries);

    for (let i = 0; i < listOfCountries.length; i++) {
        console.log(listOfCountries[i].name);
    }
}

console.log(await getTeamsFromUrl());

In the other hand, if I use forEach, I get this error message: listOfCountries.forEach is not a function

let x = listOfCountries.forEach(country => {
     console.log(country.name);
});

Thanks in advance!

Advertisement

Answer

The “JSON” from the original gist is valid JavaScript, not JSON. You could (but don’t) run the text through eval to obtain an Array object. Better still would be to download it and use it on the RHS of an assignment statement, possibly to convert it to JSON if you wanted to save it somewhere:

let listOfCountries =  paste-raw-downloaded-gist-content-here; // assign as an array literal
let json = listOfCountries.stringify();         // serialize as JSON text 

The reasons why the JavaScript is not valid JSON are

  1. property names have to be in double quotes, as in "country" and "code" instead of being unquoted,
  2. string values need to be in double quotes, as in "Ă…land Islands" and "AX" instead being single quoted.

Trying to simplistically convert the gist into JSON with string replacements can lead to problems with the back slash escaped single quote in 'Cote D'Ivoire' that using the gist in JavaScript source avoids.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement