gpt4 book ai didi

javascript - 操纵 JavaScript 数组

转载 作者:行者123 更新时间:2023-11-30 17:11:46 29 4
gpt4 key购买 nike

我希望你能帮助我。如何转换这个扁平的 JavaScript 数组,来自:

[    {"state":"First State","district":"First District","local_district_id":1,"zone_id":117,"center_id":"A","center_name":"Voting Center First"},    {"state":"First 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"},]

进入嵌套数组,像这样:

[{    "state": "First State",    "children": [{        "district_name": "First District",        "children": [{            "local_district_id": 1,            "zone_id": 117,            "center_id": "A",            "center_name": "Voting Center Name First",        }, {            "local_district_id": 2,            "zone_id": 117,            "center_id": "B",            "center_name": "Voting Center Name Second",        }, {            "local_district_id": 6,            "zone_id": 117,            "center_id": "C",            "center_name": "Voting Center Name Third",        }]    }]}]

最佳答案

你可以做这样的事情来让它在一个循环中工作。这不是最漂亮的功能,但它可以在没有大量额外开销的情况下完成工作。

<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>

关于javascript - 操纵 JavaScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26855157/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com