我想在另一个对象中获取对象的名称。 这些是我的目标:
{
"events": {
"EED8A79F-B374-4AE6-BA6F-B7B98D9D7142": {
"name": "Defeat the renegade charr.",
"level": 42,
"map_id": 20,
"flags": [],
"location": {
"type": "sphere",
"center": [ -9463.6, -40310.2, -785.799 ],
"radius": 2500,
"rotation": 0
}
},
"3A2B85C5-DE73-4402-BD84-8F53AA394A52": {
"name": "Bonus Event: Cull the Flame Legion",
"level": 80,
"map_id": 929,
"flags": [ "group_event" ],
"location": {
"type": "cylinder",
"center": [ -38.7202, -176.915, -892.494 ],
"height": 2027.5,
"radius": 10314.4,
"rotation": 0
}
},
"CEA84FBF-2368-467C-92EA-7FA60D527C7B": {
"name": "Find a way to open the door and escape the armory.",
"level": 8,
"map_id": 19,
"flags": [ "group_event" ],
"location": {
"type": "poly",
"center": [ -45685.2, -13819.6, -1113 ],
"z_range": [ -2389, 163 ],
"points": [
[ -49395.8, -15845.5 ],
[ -42699.7, -15794.1 ],
[ -43053, -14081.4 ],
[ -43629.7, -11725.4 ],
[ -49647.8, -11651.7 ]
]
}
},
...
}
}
我使用这段代码获取“events”对象中的所有对象并将它们保存在localStorage中:
$.each(data.events, function(index, value) {
localStorage.setItem("Event" + event_count, data.events);
event_count++;
});
但是现在我的localStorage是这样的:
如何获取对象名称而不是整个对象?我可以通过使用data.events.level,data.events.map_id来获取level,map_id等,但是如何获取对象名称,例如:“EED8A79F-B374-4AE6-BA6F-B7B98D9D7142”
提前致谢:)
答案 0 :(得分:3)
localStorage
无法存储对象,只能存储字符串(它会在传递的不是字符串的任何内容上调用.toString
,因此您会看到[object Object]
)。
要存储对象,请使用JSON.serialize()
进行编写,然后使用JSON.parse()
进行阅读。
在$.each
循环中,当前事件的GUID将位于index
变量中。
答案 1 :(得分:0)
尝试,
$.each(data.events, function(index, value) {
localStorage.setItem("Event" + event_count,value.name);
event_count++;
});