I am new and still exploring displaying and mapping data in React JS.
I want to display the nested data array objects but it behave that I wanted.
Here is the data:
{
name: {},
tld: [],
subregion: "Western Europe",
languages: {
fra: "French",
gsw: "Swiss German",
ita: "Italian",
roh: "Romansh"
},
I want to display also the language object data but it always returns an error.
Here is the code blocks on how I tried to observe the behavior of the data:
console.log(countries)
countries.map(country => {
console.log('Name:', country.name.common)
console.log('Area:', country.area),
console.log('Language:', country.languages)
// Object.keys(country.languages).map((language) => {
// console.log(language)
// })
});
I tried using Object.keys but it also returns an error
ShowCountry.jsx:7 Uncaught TypeError: Cannot convert undefined or null to object
I also tried using .map()
{countries.map(country => (
<div>
<p>Country: {country.name.common}</p>
<p>Area: {country.area}</p>
<h3>Languages</h3>
<ul>
{/* {country.languages.map((language) => (
<li>{language}</li>
))ther
} */}
</ul>
</div>
))
}
It returns an error that country.languages.map is not a function and I suspect maybe its null or empty. This method is what I usually see in the Stackoverflow questions and It should supposed to work but I noticed that the language is an object language: {…} while the other questions are array objects such as array: [{…}, {…}].
I think the problem is easy but I cant figure out the problem. Can you help me out and also give a little bit of explanation or related links about this.
3
Answers
Based on the image you’ve provided and your question, as far as I’m concerned, it appears that you’re trying to represent an object as an array.
you can use
Object.keys()
And to address the error
ShowCountry.jsx:7 Uncaught TypeError: Cannot convert undefined or null to object
, You will add the checkcountry.languages &&
to construct the code as follows.To display the languages, you need to iterate over the keys and values of the languages object. Here’s how you can do it: