How do you output the data from an object with dynamic properties. I have got an array of objects from an api call. This array contains one object named languages, they key value pair of this object are dynamic, so how to out put the data? I can output the name of the countries, capitals and flags but languages object which has dynamic properties I am not able to output it.
`
export default class CountryList extends React.Component {
state = {
countries: []
}
componentDidMount() {
axios.get(`https://restcountries.com/v3.1/all`)
.then(res => {
const countries = res.data;
console.log(countries)
this.setState({ countries });
})
}
render() {
this.state.countries.sort((a, b) => a.name.common > b.name.common ? 1 : -1,)
return (
< div >
{
this.state.countries.map((item, index) => (
<p key={index}> {item.name.common} {item.flag} {item.capital} {item.name.official} </p>
))
}
</ div >
)
}
}
`
I tried but this didn't work to show the data from languages for each country
this.state.countries.map((item, index) => {
for (const iterator in item.languages) {
console.log(iterator, item.languages[iterator]);
}
});
CodePudding user response:
As anticipated in the comments, you can use Object.values()
(or Object.entries()
if you want to use the language keys too) to get an array of all languages and Array.prototype.map()
to display them.
You should end up with something like:
export default class CountryList extends React.Component {
constructor() {
super();
this.state = {
countries: []
};
}
componentDidMount() {
axios.get(`https://restcountries.com/v3.1/all`).then(res => {
const countries = res.data.sort((a, b) => (a.name.common > b.name.common ? 1 : -1));
this.setState({ countries });
});
}
render() {
if (this.state.countries.length <= 0) return null;
return (
<div>
{this.state.countries.map((item, index) => (
<div key={index}>
<p>
{item.name.common} {item.flag} {item.capital} {item.name.official}
</p>
{item.languages && (<ul>
{Object.entries(item.languages).map(([lkey, language]) => (<li key={`${index}-${lkey}`}>{language}</li>))}
</ul>)}
</div>
))}
</div>
);
}
}
CodePudding user response:
Assume countries
look like this:
const countries = [
{
// other properties
languages: [
{ eng: "English" },
{ hin: "Hindi" },
// ...
]
}
]
for(const country of countries) {
for(const language of country.languages) {
// notice that this is a for... in loop instead of a for... of loop
for(const langKey in language) {
console(langKey) // i.e. eng
console.log(language[langKey]) // i.e. English
}
}
}
And if you need to render the languages as HTML elements:
countries.map(({ languages }) =>
languages.map(language =>
Object.entries(language).map(([langKey, lang]) => (
<div>
{/* i.e. eng */}
{langKey}
{/* i.e. English */}
{lang}
</div>
))
)
)