我希望你能帮助我。如何从以下位置转换此平面JavaScript数组:
[
{“州”:“第一州”,“区”:“第一区”,“ local_district_id”:1,“ zone_id”:117,“ center_id”:“ A”,“ center_name”:“ Voting Center First”},
{“州”:“第一州”,“区”:“第一区”,“ local_district_id”:2,“ zone_id”:117,“ center_id”:“ B”,“ center_name”:“第二投票中心”},
{“州”:“第一州”,“区”:“第一区”,“ local_district_id”:6,“ zone_id”:117,“ center_id”:“ C”,“ center_name”:“ Voting Center Third”},
]
放入一个嵌套数组,如下所示:
[{
“ state”:“ First State”,
“儿童”:[{
“ district_name”:“第一区”,
“儿童”:[{
“ local_district_id”:1,
“ zone_id”:117,
“ center_id”:“ A”,
“ center_name”:“首先投票中心名称”,
},{
“ local_district_id”:2
“ zone_id”:117,
“ center_id”:“ B”,
“ center_name”:“第二投票中心名称”,
},{
“ local_district_id”:6
“ zone_id”:117,
“ center_id”:“ C”,
“ center_name”:“投票中心名称第三”,
}]
}]
}]
最佳答案
您可以执行类似的操作以使它在单个循环中工作。不是最漂亮的功能,但它可以完成工作而没有很多额外的开销。
<script>
var original = [
{"state":"First State","district":"First District","local_district_id":1,"zone_id":117,"center_id":"A","center_name":"Voting Center First"},
{"state":"Second State","district":"First District","local_district_id":2,"zone_id":117,"center_id":"B","center_name":"Voting Center Second"},
{"state":"First State","district":"First District","local_district_id":6,"zone_id":117,"center_id":"C","center_name":"Voting Center Third"},
];
var statesUsed = {};
var districtsUsed = {};
var newArray = [];
var stateIndex = 0;
var districtIndex = 0;
for (var i=0,l=original.length;i<l;i++) {
var state = original[i].state;
var district = original[i].district;
var local_district_id = original[i].local_district_id;
var zone_id = original[i].zone_id;
var center_id = original[i].center_id;
var center_name = original[i].center_name;
if (statesUsed[state] == undefined) {
statesUsed[state] = stateIndex;
stateIndex++;
newArray.push({state : state, children : []});
}
districtsUsed[state] = (districtsUsed[state] == undefined) ? {} : districtsUsed[state];
if (districtsUsed[state][district] == undefined) {
newArray[statesUsed[state]].children.push({district_name : district, children : []});
districtsUsed[state][district] = newArray[statesUsed[state]].children.length - 1;
}
newArray[statesUsed[state]].children[districtsUsed[state][district]].children.push({
local_district_id : local_district_id,
zone_id : zone_id,
center_id : center_id,
center_name : center_name
});
}
</script>