【发布时间】:2019-09-16 23:44:14
【问题描述】:
我有我的 REACT JS 客户端和服务器端的 php API。我的 API 调用以以下格式获取 JSON 数据(我在 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"
}
]
}
}
上面的代码就像一个数组,其中包含每个公司项目的数组。有的公司有2 项,有的有 3 项,有的只有 1 项。现在我有我的 REACT JS,我想在其中调用 php API 并将其保存在 JSON 数据之上以这样一种格式,即我将每个公司的项目分别保存在单独的数组中(动态) .
我需要遍历上述 JSON 数据并将其拆分为与存在的唯一公司一样多的数组。就像上面的数据有 3 个不同公司的项目 所以我想将此 JSON 拆分为 3 个不同的数组,但如果我有 15 个不同的公司,那么我想拆分并保存它15 个不同的数组。我对使用 AXIOS 调用 REACT API 的粗略想法如下:
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"); }
});
请我帮助我如何动态将我的项目(按公司名称分组)保存在每个公司的单独数组中。 请帮忙!
附: mySQL Group BY 查询在这里没有帮助。我只需要 React API 调用方面的帮助。谢谢阅读。
编辑: 我想将数据存储在数组中(以公司名称命名) 像数组 Masterautomotives[ ] 应该有以下数据:
[
{
"SparePartID": "43",
"Name": "Oil and Lubricants",
"Price": "4500",
"VendorID": "48",
"CompanyName": "Master Automotives"
},
{
"SparePartID": "45",
"Name": "Lights",
"Price": "2300",
"VendorID": "48",
"CompanyName": "Master Automotives"
}
]
数组RepairSolutions[ ]应该有以下数据:
[
{
"SparePartID": "47",
"Name": "Steering Wheel",
"Price": "1500",
"VendorID": "60",
"CompanyName": "Repair Solutions"
}
]
对于其他从 API 调用中获取的公司,依此类推。
【问题讨论】:
-
提供一个你想要的数据结构的例子
-
@RomanUnt 我已经编辑了代码以提供示例。我希望这是你想要的。
标签: arrays json reactjs api axios