Home > Software engineering >  how to loop throgh array of object from axios json respone in react js and set them in div?
how to loop throgh array of object from axios json respone in react js and set them in div?

Time:01-02

I am new to react js, I am trying to fetch the data from the DB and display it on a webpage. successfully fetched the data from DB as JSON using Axios, but I don't know how to loop the object inside the array. I tried to use the map function but it's not working because of response has multiple objects in a single array. can anyone help me to fix this?

this is my json

    {
    "selva": [
        {
            "cus_id": "1",
            "name": "selva",
            "loc_name": "chennai",
            "loc_phone": "986478393",
            "loc_email": "[email protected]"
        },
        {
            "cus_id": "1",
            "name": "selva",
            "loc_name": "Trichy",
            "loc_phone": "123456789",
            "loc_email": "[email protected]"
        }
    ],
    "ram": [
        {
            "cus_id": "3",
            "name": "ram",
            "loc_name": "tnager",
            "loc_phone": "45654345",
            "loc_email": "[email protected]"
        }
    ],
    "Sam": [
        {
            "cus_id": "4",
            "name": "Sam",
            "loc_name": "chrompet",
            "loc_phone": "234545634",
            "loc_email": "[email protected]"
        },
        {
            "cus_id": "4",
            "name": "Sam",
            "loc_name": "mount",
            "loc_phone": "234545634",
            "loc_email": "[email protected]"
        },
        {
            "cus_id": "4",
            "name": "Sam",
            "loc_name": "adambakkam",
            "loc_phone": "45654345",
            "loc_email": "[email protected]"
        }
    ]
}

and this is how I fetched the data in react js and stored in array

    componentDidMount(){
    let formData = new FormData();
    formData.append("f_SearchWord", "null");
    const url = "http://localhost/cusPHP/dashAllCustomer.php";
    const config = {
      headers: { "content-type": "multipart/form-data" },
    };
    axios.post(url, formData, config).then((result) => { 
     this.setState({jData: result.data})   
    });

  }

this is the output I am looking for on the webpage, one customer name, multiple phones, email, location in one div, next customer on next div.

OUTPUT

this is the react page code

<div className="commodities">
                <div className="grid-x">
                  <div className="cell large-12">
                    <h2>Customers</h2>
                     
                  </div>
                </div>
                <div className="grid-x small-up-12">

                { 
                     


                 //loop the data
                  
                }
                  <div className="cell">
                    <div className="callout">
                      <div className="grid-x">
                        <div className="cell large-3">
                          <h3>name</h3>
                        </div>
                        <div className="cell large-9">
                          <div className="table-break">
                            <div className="grid-x">
                              <div className="cell medium-4">
                                <div className="grid-x">
                                  <div className="cell large-12">
                                    <span>location name</span>
                                  </div>
                                </div>
                              </div>
                              <div className="cell medium-3">
                                <span>Phone Number</span>
                              </div>
                              <div className="cell medium-3">
                                <span>Email Address</span>
                              </div>
                              <div className="cell medium-2">
                                <input
                                  type="button"
                                  className="label label-button float-right"
                                  value="Edit"
                                  onClick={this.EdittogglePopup}
                                />
                              </div>
                            </div>
                          </div>
                          <div className="table-break">
                            <div className="grid-x">
                              <div className="cell medium-4">
                                <div className="grid-x">
                                  <div className="cell large-12">
                                    <span>location name</span>
                                  </div>
                                </div>
                              </div>
                              <div className="cell medium-3">
                                <span>Phone Number</span>
                              </div>
                              <div className="cell medium-3">
                                <span>Email Address</span>
                              </div>
                              <div className="cell medium-2">
                                <input
                                  type="button"
                                  className="label label-button float-right"
                                  value="Edit"
                                  onClick={this.EdittogglePopup}
                                />
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

can anyone help me with this?

CodePudding user response:

You can loop through them like this:

{this.state.jData && Object.keys(this.state.jData).map(key => (
  <>
    {this.state.jData[key].map(data => (
      <div className="cell large-3">
        <h3>{data.name}</h3>
      </div>
    ))}
  </>
))}

CodePudding user response:

You are trying to iterate an object. Hence you cannot directly use "map" as an option. You can try as below to iterate:

var jData = {
  "selva": [{
      "cus_id": "1",
      "name": "selva",
      "loc_name": "chennai",
      "loc_phone": "986478393",
      "loc_email": "[email protected]"
    },
    {
      "cus_id": "1",
      "name": "selva",
      "loc_name": "Trichy",
      "loc_phone": "123456789",
      "loc_email": "[email protected]"
    }
  ],
  "ram": [{
    "cus_id": "3",
    "name": "ram",
    "loc_name": "tnager",
    "loc_phone": "45654345",
    "loc_email": "[email protected]"
  }],
  "Sam": [{
      "cus_id": "4",
      "name": "Sam",
      "loc_name": "chrompet",
      "loc_phone": "234545634",
      "loc_email": "[email protected]"
    },
    {
      "cus_id": "4",
      "name": "Sam",
      "loc_name": "mount",
      "loc_phone": "234545634",
      "loc_email": "[email protected]"
    },
    {
      "cus_id": "4",
      "name": "Sam",
      "loc_name": "adambakkam",
      "loc_phone": "45654345",
      "loc_email": "[email protected]"
    }
  ]
};

Object.keys(jData).map(val => {
  jData[val].map(cusData => {
    //Print your data here
    console.log(cusData['loc_name']);
    console.log(cusData['loc_phone']);
  });
});

This is an idea to iterate your object. But please make sure your json is not too large. Otherwise it'll hit your performance and then you might have to find alternative way to print your data.

CodePudding user response:

Here you go

export default function DetailTable({data}) {

  return (
      <div className="grid-x small-up-12">
        <BuildDetailTable data={data} />
      </div>
    );
}

const BuildDetailTable = ({ data }) => {
  const result = [];
  for (const [key, value] of Object.entries(data)) {
    result.push(
      <div className="cell">
        <div className="callout">
          <div className="grid-x">
            <div className="cell large-3">
              <h3>{key}</h3>
              <BuildDetailRow data={value} />
            </div>
          </div>
        </div>
      </div>
    );
  }
  return result;
};

const BuildDetailRow = ({ data }) => {
  const result = [];
  for (const item of data) {
    result.push(
      <div className="cell large-9">
        <div className="table-break">
          <div className="grid-x">
            <div className="cell medium-4">
              <div className="grid-x">
                <div className="cell large-12">
                  <span>Name: {item.loc_name}</span>
                </div>
              </div>
            </div>
            <div className="cell medium-3">
              <span>Phone: {item.loc_phone}</span>
            </div>
            <div className="cell medium-3">
              <span>Email: {item.loc_email}</span>
            </div>
            <div className="cell medium-2">
              <input
                type="button"
                className="label label-button float-right"
                value="Edit"
              />
            </div>
          </div>
        </div>
      </div>
    );
  }

  return result;
};

Is you pass the api data to DetailTable component, it will render the desired result

<DetailTable data={data from api}/>
  • Related