我正在尝试从 angular 对象数组中获取数据:
我的代码结构:
storegeArray: any [];
填写数组“-”中的所有字段:
this.storegeArray = new Array(100).fill("-");
将数据推送到特定 id 的数组中:
this.storegeArray[data.vehicle_id] = {x: location[1], y: location[0]};
在本地存储中保存数组 (storegeArray):
localStorage.setItem("coordinates",this.storegeArray);
到这里一切正常。
console.log(this.storegeArray)
输出 :
(100) ["-", "-", "-", {…}, "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-"]
0: "-"
1: "-"
2: "-"
3: {x: 33.8953628, y: 35.4906471}
4: "-"
5: "-"
6: "-"
7: "-"
8: "-"
.......
工作正常我在 id = 3 id of data.vehicle_id 中有数据
在全局情况下,我在数组中的不同索引中有多个数据,因此我使用此方法获取:
const myArrayFromLocalStorage = localStorage.getItem('coordinates');
if (myArrayFromLocalStorage) {
for(let i=0; i<myArrayFromLocalStorage.length; i++){
if(JSON.stringify(myArrayFromLocalStorage[i] != "-")){
console.log(JSON.stringify(myArrayFromLocalStorage[i]));
}
}
}
输出:
"-"
","
"-"
","
"-"
","
"["
"o"
"b"
"j"
"e"
"c"
"t"
" "
"O"
"b"
"j"
"e"
"c"
"t"
"]"
","
"-"
","
"-"
","
"-"
我尝试做的是获取数组以查看数据(对象)而不是“-”并获取此数据(对象),这意味着获取 x 和 y 。
我做错了什么?
由于您通过 id 保存车辆的数据,因此最好使用对象而不是数组。那么你就不需要检查它是否是-
。
this.storage = {};
this.storage[data.vehicle_id] = {x: location[1], y: location[0]};
localStorage.setItem('data', JSON.stringify(this.storage)); // to save the data
const dataFromLocalStorage = JSON.parse(localStorage.getItem('data') || '{}'); // to get the data from localStorage
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句