如何在React中推送JSON Object数组中的项目?

时间:2019-05-03 01:58:49

标签: arrays json reactjs object setstate

我有我的REACT JS客户端,并使用PHP API来获取数据。我从API调用中获取JSON对象数组,格式如下:

{
    "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"
            }
        ]
    }
}
 从API响应中,我想在 myrecords [] 的this.state(最初为空)中保存以上响应数据(NAME和PRICE),此外,我还想在上面添加更多项目JSON,就像每个 SPAREPART 一样,我想为每个数据添加“ 数量”和“ 总价格”。

我正在尝试使用 .push 方法为每个数据项添加这些数量和总计价格。这是我的REACT API调用,我在这里获取数据并通过 myrecords [] setState 保存并在其中推送更多项,但它不起作用并显示错误消息。请帮助,请教我如何正确推送物品。

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

1 个答案:

答案 0 :(得分:1)

您可以将对象转换为数组并进行赋值

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