如何在 REACT JS API 调用中迭代 JSON 嵌套数组?

Posted

技术标签:

【中文标题】如何在 REACT JS API 调用中迭代 JSON 嵌套数组?【英文标题】:How to iterate JSON nested array in REACT JS API call? 【发布时间】: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 我已经编辑了代码以提供示例。我希望这是你想要的。 【参考方案1】:

你想用这些数据做什么?您是否将它们直接保存到州?您基本上可以直接从 API 响应中以所需格式访问它,就像 response.records 的属性一样。我想不出您需要将数组单独放入状态中的用途,因此将整个记录对象保存到状态然后使用 state.records["Company name" 访问所需公司的数据可能更有意义],它将准确返回您正在寻找的数据结构。然后,您可以映射对象的键并依次映射其中包含的每个数组,以呈现按公司分组的所有产品。

  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");  
       );

然后你可以渲染每个公司的零件列表:

  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>
    )
  

看到这个Codepen。

【讨论】:

非常感谢。这就是我想要的。为什么我想要单独数组中的数据是因为在下一个订单处理步骤中,我想分别创建每个公司的订单。那么对于创建订单,我还能像 this.state.records[company] 那样使用这种方式吗? 没错。需要明确的是,此处使用的公司参数只能在对象键的映射函数中访问,但所有数据始终在 this.state.records["company name"] 中可用。【参考方案2】:

试试下面的代码,应该能帮到你

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

【讨论】:

短版代码是 let compaines = Object.values(response.data.records); 非常感谢。这也回答了我的问题。

以上是关于如何在 REACT JS API 调用中迭代 JSON 嵌套数组?的主要内容,如果未能解决你的问题,请参考以下文章

map 函数没有在 react.js 中迭代状态对象(数组格式)

如何在django api调用的react js中使用来自post请求的响应部分的数据?

在 react js 中进行 API 调用的正确方法是啥?

在 React.js 的功能组件中首次渲染之前调用 api

如何根据 React js 中 api 的响应显示成功或错误消息

如何使用 formdata 将图像文件发送到 React/Next js api?