如何在REACT js中从JSON对象正确删除特定项目?

时间:2019-05-04 07:39:01

标签: javascript json reactjs state

在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 来执行删除操作。

它可以完美完成并删除我单击的项目。

但是问题是,如果某公司只有一个项目并且我将其删除,则 myreocords JSON对象仍然包含该公司的数组为空(无项目)。 相反,我希望它删除没有任何项目的公司。

状态为 myrecords 的SO仅应包含存在其项目的 Company 数据。

请帮助我解决此问题。

1 个答案:

答案 0 :(得分:3)

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

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

 }