【发布时间】:2019-09-22 14:22:18
【问题描述】:
我有一个 REACT JS 应用程序,其中 JSON 对象 CartObj 以这种格式存储在 localStorage 中:
{
"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"
}
]
}
我想获取上述 JSON 对象 的长度,该对象存储在我的 localStorage 中作为“CartObj”。正如我们所看到的,上面的数据总共有 6 (六) 个不同的产品,所以我想得到一个等于 6 的长度。
我使用了下面的代码,但它得到了一个非常大 值,例如 23876:
const lenObj = JSON.stringify(localStorage.getItem('storeObj'));
const len = lenObj.length;
console.log("JSON obj length: ",len);
请帮助我如何以正确的方式获取此 JSON 对象的长度。
【问题讨论】:
标签: arrays json reactjs local-storage