简体   繁体   中英

how to map nested json data in react js

how to map one nested json data in react js example i want to display the product images that i recived from api

export class Planview extends Component{
 constructor() {
 super();
 this.state = {
 package: [],
 };
 }
componentDidMount() {
const ProdID = this.props.match.params.ProductID
fetch(`http://127.0.0.1:8000/api/plan/${ProdID}/`)
.then(response => response.json())
.then(responseData => { 
  this.setState({
    package: responseData
  });
})
.catch(error => {
  console.log('Error fetching and parsing data', error);
});
}
render(){
return(<>
<div className="container mar" >
    <h1 className="my-4">{this.state.package.title}</h1>
<div className="row">
    <div className="col-md-offset-2">
        <div className="row" id="gradient">
            <div className="col-md-6 img-responsive">
                <img 
                className ="img-main img"
                src={"http://127.0.0.1:8000"+this.state.package.thumbnail}
                alt="main" 
                fluid ="True"/>
            </div>
            <div className="col-md-6" id="overview">
                <h4>{this.state.package.code}</h4>
                <h5><small>  {this.state.package.created_at}</small></h5
            </div>
            <div className="row mt-4">
                <h3><small></small></h3>
                <div className="row">
                { 
                this.state.package.image.map(function (person, index) {
                 return (
                    <div className="col" key={index}>
                            <img className={person.image} src="" alt="1"/>
                    </div>
                 )})}
                </div>
            </div>

        </div>
        
        <div className="row">
        <h3 className="my-4">{this.state.package.description}</h3>
        </div>
    </div>
</div>
</div>
</> );
}
}
export default Planview;

and my json is like

`{id: 1, image: [{image: "/media/plan_images/Home-5-E-plan-1024x684.jpg"},…], 
 title: "sample",…}`
 

expand of json like

`code: "MAG0001"
 created_at: "2020-11-23"
 description: "college book"
 details: {age: 31, city: "New York", name: "John"}
 id: 1
 image: [{image: "/media/plan_images/Home-5-E-plan-1024x684.jpg"},
 {image: "/media/plan_images/Home-4-E-plan-1024x684.jpg"},
 {image: "/media/plan_images/Home-3-E-plan-1024x684.jpg"},
 ]
 slug: "sample"
 thumbnail: "/media/plan_images/900-square-feet-home-plan.jpg"
 title: "sample"`

from the above json i want to display the image from the field image array it contains multiple images and also the json data in the field name details

You are putting a json object inside an array and trying to map it in the render method,map function is only used for array, here is the detail.There is 2 ways to solve this problem

Solution 1:

fetch(url)
     .then(res=>{
        this.setState({package:[...this.state.package,res.json()]}) 
        //using es6
     })
     .catch(err=>{
        console.log(err)
     })

render(){
    return(<>
    {this.state.package.map(e=>{
        return e.properties // iterate the json attribute
    })}
    </>)
}

Solution 2: You can convert the json object into array using a foreach loop, here is the details

Hooray finally thanks to Sarun UK i got the answer

i changed

constructor() {
    super();
    this.state = { package:{ image: []}, };
  }

and

{ this.state.package.image && this.state.package.image.map(function (person, index) {
                 return (
                    <div className="col" key={index}>
                            <img className="img-fluid" src= 
 {"http://127.0.0.1:8000"+person.image} alt="1"/>
                    </div>
)})} 

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