lix
lix

Reputation: 52

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!

Upvotes: 0

Views: 586

Answers (3)

traktor
traktor

Reputation: 19301

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.

Upvotes: 1

Rich N
Rich N

Reputation: 9475

response.data is returning a string that needs to be parsed into an array. It's also returning a string that isn't valid JSON, so needs a little bit of work on it to create valid JSON.

The code below does this from your original URL and prints out the country names:

const axios = require('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;
    const jsonListOfCountries = listOfCountries.replace(/name:/g, '"name":').replace(/code:/g, '"code":').replace(/'/g, '"');
    const countries = JSON.parse(jsonListOfCountries);
    for (let i = 0; i < countries.length; i++) {
        console.log(countries[i].name);
    }
}

(async function MyFunc() {
    console.log(await getTeamsFromUrl());
})();

Upvotes: 2

Ozgur Sar
Ozgur Sar

Reputation: 2204

Your code is fine but your source json was invalid. This is tested an it works from another source.

const getTeamsFromUrl = async() => {
    const url = 'https://raw.githubusercontent.com/samayo/country-json/master/src/country-by-name.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].country);
    }
}
getTeamsFromUrl();

Upvotes: 1

Related Questions