YellowMinion
YellowMinion

Reputation: 242

How to iterate JSON nested array in REACT JS API call?

I have my REACT JS client side and php API on server side. My API call fetches the JSON data in the below format(I tried it on POSTMAN):

{
    "records": {
        "Master Automotives": [
            {
                "SparePartID": "43",
                "Name": "Oil and Lubricants",
                "Price": "4500",
                "VendorID": "48",
                "CompanyName": "Master Automotives"
            },
            {
                "SparePartID": "45",
                "Name": "Lights",
                "Price": "2300",
                "VendorID": "48",
                "CompanyName": "Master Automotives"
            }
        ],
        "Repair Solutions": [
            {
                "SparePartID": "47",
                "Name": "Steering Wheel",
                "Price": "1500",
                "VendorID": "60",
                "CompanyName": "Repair Solutions"
            }
        ],
        
         "FiveStar Automotives": [
            {
                "SparePartID": "51",
                "Name": "Brakes",
                "Price": "234",
                "VendorID": "70",
                "CompanyName": "FiveStar Automotives"
            },
            {
                "SparePartID": "53",
                "Name": "Clutch",
                "Price": "999",
                "VendorID": "70",
                "CompanyName": "FiveStar Automotives"
            },
              {
                "SparePartID": "55",
                "Name": "LED",
                "Price": "288",
                "VendorID": "70",
                "CompanyName": "FiveStar Automotives"
            }
        ]
    }
}

This above code is like an array which contains arrays of each company's items. Some Company has 2 items, some has 3 and some has only 1 item. Now I have my REACT JS where I wanna call the php API and save this above JSON data in such a format that I save each Company's items separately in separate arrays (dynamically).

I need to iterate through the above JSON data and split it into as many arrays as the unique Companies present. Like above data has has 3 distinct companies' items so I wanna split this JSON into 3 different arrays but if I had 15 different Companies then I would like to split and save it in 15 different arrays. My rough idea of REACT API call using AXIOS is below:

  axios.post('http://localhost/Auth/api/customers/show_cart.php', 
     {
    headers: {'Accept': 'application/json, text/plain, */*',
              'Content-Type': 'application/json'}
    } )
    .then(response => {

    //I need to know what to write here to save the data in my required format

      })
     .catch(error => {
     if (error) {
       console.log("REACT Error. Cannot show cart items");  }
       });

Please I need Help how to dynamically save my items (Grouped By Company Names) in separate arrays for each Company. Please Help!

P.S. mySQL Group BY query doesn't help here. I just want help in React API call. Thanks for reading.

EDIT: I want to store the data in arrays(named on Company Names) like array Masterautomotives[ ] should have this data below:

 [
                {
                    "SparePartID": "43",
                    "Name": "Oil and Lubricants",
                    "Price": "4500",
                    "VendorID": "48",
                    "CompanyName": "Master Automotives"
                },
                {
                    "SparePartID": "45",
                    "Name": "Lights",
                    "Price": "2300",
                    "VendorID": "48",
                    "CompanyName": "Master Automotives"
                }
  ]

And Array RepairSolutions[ ] should have following data:

 [
            {
                "SparePartID": "47",
                "Name": "Steering Wheel",
                "Price": "1500",
                "VendorID": "60",
                "CompanyName": "Repair Solutions"
            }
  ]

and so on for rest of the Companies whoever is being fetched from API call.

Upvotes: 1

Views: 2666

Answers (2)

Chris B.
Chris B.

Reputation: 5763

What are you trying to do with this data? Are you saving them directly to the state? You basically have access to it in your desired format directly from the API response, just as properties of response.records. I can't think of what you would need arrays separately put into the state for, so it may make more sense to just save the entire records object to the state and then access the desired company's data using state.records["Company name"], which will return exactly the data structure you're looking for. You can then map over the object's keys and in turn over each array contained within to render all of the products grouped by company.

  axios.post('http://localhost/Auth/api/customers/show_cart.php', 
     {
    headers: {'Accept': 'application/json, text/plain, */*',
              'Content-Type': 'application/json'}
    } )
    .then(response => {
      this.setState({
         records: response.records
      })

      })
     .catch(error => {
     if (error) {
       console.log("REACT Error. Cannot show cart items");  }
       });

And then you can render lists of each company's parts:

  render() {
    return (
      <div>
        {Object.keys(this.state.records).map((company, i) => (
        <div key={company}>
          <h2>{company}</h2>
          <ul>
           {this.state.records[company].map((product, i) => (
              <li>{product["Name"]} - ${product["Price"]}</li>
            ))}
          </ul>
        </div>
        ))}
      </div>
    )
  }
}

See this Codepen.

Upvotes: 1

Atul
Atul

Reputation: 3423

Try below code, it should help you

.then(response => {
    let companies = [];
    let companiesData = response.data.records;;
    for (let company in companiesData)
    {
      companies.push(companiesData[company])
    }
    console.log(companies); 
})

Upvotes: 1

Related Questions