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:

JavaScript

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

JavaScript

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:

JavaScript

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