简体   繁体   中英

How to access nested JSON object in React native using map method?

I want to list the JSON object inside a card. Following is my JSON data.

[
   {
      "data":{
         "name":"Economy",
         "categories":[
            {
               "id":28,
               "name":"Economy",
               "slug":"economy",
               "image":"https://asdfghh/gjnk/User-default-image-boy.png"
            }
         ],
         "instructor":{
            "id":"24",
            "name":"asdfg",
            "avatar":"https://asdfgh/fghj/User-default-image-boy.png",
            "sub":""
         },
         "menu_order":0
      },
      "headers":[

      ],
      "status":200
   },
   {
      "data":{
         "name":"MCQ",
         "categories":[

         ],
         "instructor":{
            "id":"1",
            "name":"qwertyy",
            "avatar":"https://asdfgh//bpthumb.jpg",
            "sub":""
         },
         "menu_order":0
      },
      "headers":[

      ],
      "status":200
   }
]

How do I map over this JSON object? I want data.categories.name , data.instructor.name to be listed inside a card, and the rendering in React is as follows:

renderCourses (){
        return this.state.courses.map(course =>
        <HomeScreen key={course.categories.name} course={course}/>)
    render(){
        console.log(this.state);
        return(

        <ScrollView>
        {this.renderCourses()}
        </ScrollView>
        );
    }
}

But nothing is showing inside the card. How can I do this?

According to your JSON data of courses, the categories inside it is a array of objects so you can't directly use course.categories.name . Inside your render try and print this as below:-

renderCourses = () => {
    return (<div>
        {this.state.courses.map((course, index)=> <HomeScreen key={course.categories[0].name || index} course={course}/>)}
    </div>)
}

render(){
    console.log(this.state);
    return(
        <ScrollView>
            {this.renderCourses()}
        </ScrollView>
    );
}

Let me know if this doesn't solve your problem.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM