javascript - 如何在 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状态应该只有那些项目存在的公司数据。
请帮我解决这个问题。
解决方案
如果它没有项目,您应该删除节点:
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
});
}
推荐阅读
- python - python中.find()和'in'运算符的区别
- python - 根据输入命名数据库
- javascript - 如果我不使用 cognito,如何使用 Nodejs 在 axios 中准确签署 AWS elasticsearch 搜索请求?
- python - 使用 pygame 显示多个图像
- python - 赋值中的不兼容类型(表达式的类型为“List[
]",变量的类型为 (...) - javascript - 在另一个函数内部使用时,外部 JavaScript 函数返回错误
- python - 在 venv 中安装 sdist:无法从 install_requires 安装软件包
- html - HTML 不写任何文本
- python - Pygame 填充在离开屏幕之前不会更新
- ios - 如何在reactjs中实现点击状态栏以滚动到iphone的顶部