Home > Mobile >  Listing all values of an object's property from JSON file
Listing all values of an object's property from JSON file

Time:12-24

I'm trying to list all 'languages' from a JSON file into a <li> using the rest countries API (https://restcountries.com/v3.1/all) that looks like this (example country Malta)

languages: {
eng: "English",
mlt: "Maltese"
},

My code

filteredCountries.map(country =>
          <div key={country.cca2}>
            <h1>{country.name.common}</h1>
            <>Capital: {country.capital}</><br/>
            <>Population: {country.population.toLocaleString()}</>
            <h3>Languages</h3>
            <ul>
              {Object.keys(country.languages).map(lang => { 
              <li key={lang.name}>{lang.name}</li>
            }
              )}
            </ul>
            <img src={country.flags.png} alt='Country Flag'/>
          </div>

I am able to pull the country name, capital, population and flag but unable to list the languages in an efficient manner since every country has a varied number of languages. Using Object.keys doesn't provide errors but it doesn't display what I want. I tried using country.languages.map but I get the error of TypeError: country.languages.map is not a function I was able to get the country name and capital using country.name.cca2 and country.capital respectively

CodePudding user response:

You need to use country.languages[lang] inside the Object.keys(country.languages).map()

Also because you are using lambda notation, you need to leave out the curly braces { snd } after the =>.

{Object.keys(country.languages).map(lang =>
  <li key={lang}>{country.languages[lang]}</li>
)}

Or, if you want the curlies, then the code inside the curly braces needs to use the return keyword:

{Object.keys(country.languages).map(lang =>
  {
    return <li key={lang}>{country.languages[lang]}</li>
  }
)}
  • Related