Javascript 如何重新构造此JSON以使其更易于访问
我有一些JSON数据的格式如下:Javascript 如何重新构造此JSON以使其更易于访问,javascript,json,Javascript,Json,我有一些JSON数据的格式如下: [ {"stage1" : [{ "checkpoints" : [ { "id" : "checkpoint1", "name" : "a checkpoint name 1", "purpose" : "a string about the purpose her
[ {"stage1" : [{
"checkpoints" :
[
{
"id" : "checkpoint1",
"name" : "a checkpoint name 1",
"purpose" : "a string about the purpose here",
},
{
"id" : "checkpoint2",
"name" : "a checkpoint name 2",
"purpose" : "a string about the purpose here",
}
],
"stages" :
[
{
"id" : "an id here",
"name" : "a checkpoint name 1",
"purpose" : "a string about the purpose here yah",
}
]
}
]},
{"stage2" : [{
"checkpoints" :
[
{
"id" : "checkpoint1",
"name" : "a checkpoint name 1",
"purpose" : "a string about the purpose here",
},
{
"id" : "checkpoint2",
"name" : "a checkpoint name 2",
"purpose" : "a string about the purpose here",
}
],
"stages" :
[
{
"id" : "an id here",
"name" : "a checkpoint name 1",
"purpose" : "a string about the purpose here yah",
}
]
}
]},
{"stage3" : [{
"checkpoints" :
[
{
"id" : "checkpoint1",
"name" : "a checkpoint name 1",
"purpose" : "a string about the purpose here",
},
{
"id" : "checkpoint2",
"name" : "a checkpoint name 2",
"purpose" : "a string about the purpose here",
}
],
"stages" :
[
{
"id" : "an id here",
"name" : "a checkpoint name 1",
"purpose" : "a string about the purpose here yah",
}
]
}
]},
]
目前,我必须参考以下数据才能在某个阶段获得:
alert(data[0].stage1[0].checkpoints.length);
为了获得第2阶段的数据,我必须这样做:
alert(data[1].stage2[0].checkpoints.length);
我希望能够做到的是只使用阶段名称访问数据,而不必在“data”声明后指定索引:
alert(data.stagex[0].checkpoints.length);
我不想在数据部分之后声明索引。如何重新构造JSON,以便在不首先指定索引的情况下使用stage名称获取所需数据?不要将Stage1、Stage2放在数组中。它们可以作为键直接访问不要将Stage1、Stage2放在一个数组中。它们可以作为键直接访问您有一个对象数组,每个对象只有一个属性(
stageX
)。拥有这个属性似乎一点也不必要,我只想把它移除。或者创建一个对象,将stage1
、stage2
作为属性,而不是数组。此外,检查点的长度属性如何引用这些阶段?您有一个对象数组,每个对象只有一个属性(stageX
)。拥有这个属性似乎一点也不必要,我只想把它移除。或者创建一个对象,将stage1
,stage2
作为属性,而不是数组。此外,检查点的长度属性如何引用阶段?是的,按照@Nikhil所说的,您可以将引用缩短为数据。stage1[0]。检查点@Nikhil如何将阶段从数组中取出?我已经尝试删除整个json周围的方括号,但这会创建无效的jsonYep,按照@Nikhil所说的,您可以将引用缩短到data.stage1[0]。检查点@Nikhil如何从数组中删除stage?我已经尝试删除整个json周围的方括号,但这会创建无效的json