const input = [
{ province: "广东", city: "深圳", area: "宝安" },
{ province: "广东", city: "深圳", area: "南山" },
{ province: "广东", city: "汕头", area: "潮阳" },
{ province: "广东", city: "广州", area: "天河" },
{ province: "浙江", city: "杭州", area: "西湖" },
];
function handleArea(arr) {
const districtList = [];
arr.forEach((v) => {
let index = districtList.findIndex((item) => item.value === v.province);
if (index === -1) {
districtList.push({
value: v.province,
children: [
{
value: v.city,
children: [
{
value: v.area,
},
],
},
],
});
} else {
let cityIndex = districtList[index]["children"].findIndex(
(item) => item.value === v.city
);
if (cityIndex === -1) {
districtList[index]["children"].push({
value: v.city,
children: [{ value: v.area }],
});
} else {
districtList[index]["children"][cityIndex]["children"].push({
value: v.area,
});
}
}
});
return districtList;
}
console.log(handleArea(input));
网友评论