Answer the question
In order to leave comments, you need to log in
How to display data from an associative array in React?
I have a problem with outputting data from an associative array inside elements. The bottom line is that I have a main array with data from various countries. It has 3 levels of nesting. 1. Country => 2. States => 3. Cities.
Example:
const countries = {
'USA': {
'California': {
capital: 'Sacramento',
founded: '9 сентября 1850'
population: '40000000',
motto: 'Эврика',
anthem: 'I Love You, California',
cities: {
'Los-Angeles': {
area: '1301.97',
founded: '4 сентября 1781',
population: '3 976 322'
},
'San-Diego': {
area: '963.6',
founded: '1769',
population: '1 420 000'
},
'San-Francisco': {
area: '600.6',
founded: '1776',
population: '884 363'
}
}
},
'New-York': {
capital: 'New-York',
founded: '1624'
population: '19 795 791',
motto: 'Всё выше',
anthem: 'I Love New York',
cities: {
'Buffalo': {
area: '136',
founded: '1832',
population: '261 310'
},
'Rochester': {
area: '96.1 ',
founded: '1803',
population: '208 123'
},
'Yonkers': {
area: '52.6',
founded: '1646',
population: '196 086'
}
}
}
},
'Canada': {
'Ontario': {
capital: 'Toronto',
founded: '1 июля 1867 года'
population: '13 873 933',
motto: 'От моря до моря',
anthem: 'I Love You, Ontario',
cities: {
'Ottawa': {
area: '2790.3',
founded: '1850',
population: '934 243'
},
'Leamington': {
area: '508.76',
founded: '1876',
population: '49 741'
},
'Milton': {
area: '366.61',
founded: '17 мая 1818',
population: '110 128'
}
}
},
'Québec': {
capital: 'Québec',
founded: '3 июля 1608'
population: '8 294 656',
motto: 'От моря до моря',
anthem: 'I Love Québec',
cities: {
'Montréal': {
area: '363.13',
founded: '17 мая 1642',
population: '1 942 694'
},
'Laval': {
area: '96.1 ',
founded: '1965',
population: '401 553'
},
'Gatineau': {
area: '342',
founded: '1800',
population: '265 349'
},
'Longueuil': {
area: '122.9',
founded: '1657',
population: '239 700'
}
}
},
'Alberta': {
capital: 'Edmonton',
founded: '1 сентября 1905'
population: '4 231 959',
motto: 'От моря до моря',
anthem: 'I Love Alberta',
cities: {
'Calgary': {
area: '726',
founded: '1875',
population: '1 096 833'
}
}
}
}
}
const countriesArray = {
list: [
{
id: 1,
countryName: "Russian Federation",
capital: "Moscow"
},
{
id: 2,
countryName: "China",
capital: "Beijing"
},
{
id: 3,
countryName: "Germany",
capital: "Berlin"
}
]
}
function OutCountry(props) {
return (
<div>
<h3>Country: {props.countryName}</h3>
<h3>Capital: {props.capital}</h3>
<hr/>
</div>
)
}
function App() {
const countryComponents = countriesArray.list.map(country => <OutCountry key={country.id} countryName={country.countryName} capital={country.capital} />)
return (
<div>
{countryComponents}
</div>
)
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question