I have an API which has nested objects, and within that nested arrays. I have managed to display some data on the screen with .map, i have hard coded the first row. How to a do a nested map in React Native?
I have tried various solutions on stackoverflow but so far have not found any that have matched my solution
This is an example of my API and Code
{
"Name":"Worcestershire Acute Hospitals",
"Sites":[
{
"SiteCode":"ALX",
"Statistics":[
{
"Id":3,
"Name":"Last Updated",
"Value":"29 Jul 2019 18:26:39:487",
"LastUpdated":"2019-07-29T18:32:16.833",
"ImageURL":"Ambulance"
},
{
"Id":4,
"Name":"Safety Level",
"Value":"Overwhelmed",
"LastUpdated":"2019-07-29T18:32:16.833",
"ImageURL":"Ambulance"
},
{
"Id":5,
"Name":"Todays Admissions",
"Value":"32",
"LastUpdated":"2019-07-29T18:32:16.833",
"ImageURL":"Ambulance"
},
componentDidMount() {
axios.get('http://ralxwebdev01/tod/api/tod')
.then(response => this.setState({ WrhDatas: response.data.Sites[0].Statistics }));
}
renderWrhName() {
return this.state.WrhDatas.map(wrh => <Text key={wrh.Id}>{wrh.Name}</Text>);
}
render() {
console.log(this.state.WrhDatas);
return (
<View>
<Text>
{this.renderWrhName()}
</Text>
</View>
);
}
}
I know for sites i am using [0] and the data displays on the screen. But I want to loop through sites, then loop through statistics.
I want to loop through sites, then loop through statistics.
In componentDidMount
you can do this,
this.setState({ WrhDatas: data.Sites.map(data => data.Statistics.map(stat=> stat)) },()=>console.log(this.state.WrhDatas));
This will return you the Array of Array's
.
And your renderWrhName
function should be,
renderWrhName() {
return this.state.WrhDatas.map(wrh => wrh.map(wrh => <div key={wrh.Id}>{wrh.Name}</div>));
}
Demo . (Tested with sample data provided in post)
Note: For simplicity I have used div
to render the data, but the same will work for Text
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.