首页 > 解决方案 > 如何在 REACT js 中正确地从 JSON 对象中删除特定项目?

问题描述

在 REACT JS 中,我在状态组件“ myrecords ”中有一个JSON 对象,其中项目按其公司名称分组,格式如下:

{
        "Master Automotives": [
            {
                "SparePartID": "43",
                "Name": "Oil and Lubricants",
                "Price": "4500",
                "VendorID": "48",
                "CompanyName": "Master Automotives",
                 "Qty": 1,
                 "TotalPrice": "4500"

            },
            {
                "SparePartID": "45",
                "Name": "Lights",
                "Price": "2300",
                "VendorID": "48",
                "CompanyName": "Master Automotives",
                 "Qty": 1,
                 "TotalPrice": "2300"
            }
        ],

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

         "FiveStar Automotives": [
            {
                "SparePartID": "51",
                "Name": "Brakes",
                "Price": "234",
                "VendorID": "70",
                "CompanyName": "FiveStar Automotives",
                 "Qty": 1,
                 "TotalPrice": "234"
            },
            {
                "SparePartID": "53",
                "Name": "Clutch",
                "Price": "999",
                "VendorID": "70",
                "CompanyName": "FiveStar Automotives",
                 "Qty": 1,
                 "TotalPrice": "999"
            },
              {
                "SparePartID": "55",
                "Name": "LED",
                "Price": "288",
                "VendorID": "70",
                "CompanyName": "FiveStar Automotives",
                 "Qty": 1,
                 "TotalPrice": "288"
            }
        ]
    
}

每当单击项目的删除按钮时,我都会使用此方法从myrecords状态中删除特定项目:

removeCartItem(CompanyName, sid,e)
{

  const items = {...this.state.myrecords};
  const j = items[CompanyName].findIndex(item => item.SparePartID === sid);

  items[CompanyName].splice([j], 1);

  this.setState({
     myrecords: items
   });
   
   }

我将CompanyName、 SparePartID 作为函数参数中的sid发送以执行删除。

它工作得非常好,并删除了我单击的项目。

问题是,如果一家公司只有 1 个项目并且我将其删除,那么myreocords JSON 对象仍然包含该公司的空数组(无项目)。相反,我希望它删除这样一个没有任何物品的公司。

所以myrecords状态应该只有那些项目存在的公司数据。

请帮我解决这个问题。

标签: javascriptjsonreactjsstate

解决方案


如果它没有项目,您应该删除节点:

removeCartItem(CompanyName, sid,e) {

  const items = {...this.state.myrecords};
  const j = items[CompanyName].findIndex(item => item.SparePartID === sid);

  items[CompanyName].splice([j], 1);

  // rm company node if it have no items
  if (items[CompanyName].length === 0) {
    delete items[CompanyName]
  }

  this.setState({
     myrecords: items
   });

 }

推荐阅读