0

I have my REACT JS client side and using PHP APIs to fetch data. Im fetching the JSON Object array from API call, in the following format:

{
    "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"
            }
        ]
    }
}
From API response, I want to save the above response data (NAME and PRICE) in this.state of myrecords[] (which is empty initially) Plus I also want to push some more items to this above JSON, like for each SPAREPART I want to add "Quantity" and "TotalPrice" items for each data.

Im trying to use .push method to add these Quantity & TotalPrice for each data item. here is my REACT API call where I m fetching data and saving it by setState of myrecords[] and pushing more items in it but IT DOESN'T WORK and shows ERROR msg. please HELP ME how to PUSH the items correctly.

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

      let myItems = [];
    response.data.records.forEach((item) => {
      myItems.push({SparePartID: item.SparePartID,
         Name: item.Name,
         Price: item.Price,

         Quantity: 1,
         totalPrice: item.Price});
        })

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

0

1 Answer 1

1

You can convert your object to array and foreach it

let myItems = [];
let result = Object.entries(response.records).map(( [k, v] ) => ({ [k]: v }));
    result.forEach((item) => {
      var key = Object.keys(item)[0];
      item[key].forEach((sub)=>{
      myItems.push({SparePartID: sub.SparePartID,
         Name: sub.Name,
         Price: sub.Price,

         Quantity: 1,
         totalPrice: sub.Price});
        })
});

let response = {
    "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"
            }
        ]
    }
}

let myItems = [];
let result = Object.entries(response.records).map(( [k, v] ) => ({ [k]: v }));
    result.forEach((item) => {
      var key = Object.keys(item)[0];
      item[key].forEach((sub)=>{
      myItems.push({SparePartID: sub.SparePartID,
         Name: sub.Name,
         Price: sub.Price,

         Quantity: 1,
         totalPrice: sub.Price});
        })
});

        
        console.log(myItems);

Sign up to request clarification or add additional context in comments.

6 Comments

It works fine. but for separate handling of SpareParts by each Supplier separately I want the data in JSON Object format. So How do I CONVERT this array back to my JSON Object format? Or is there any way that I PUSH items without converting it into Array?
you still keep old object, push method only use for array
ok but now when I console.log(myItems) it shows an array not object.
what object format do you want? you can use myItems[0] as object?
I want the object format I mentioned in very beginning of question. Like all items are grouped by their suppliers.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.