- 开发中需要用到省市区数据,但是后端只返回最里层城市的code值
- code是省市区的唯一代码,name则是省市区的名称,children则是省市区下的子项
function getArea(json, code) {
let names = [];
let codes = [];
function findCity(list, code, father) {
const index = list.findIndex(ev => ev.code == code);
if (index > -1) {
const child = list[index];
names.unshift(child.name);
codes.unshift(child.code);
father && names.unshift(father.name) && codes.unshift(father.code);
father && findCity(json || [], father.code);
return;
}
list.map(item => {
if (item.children) {
findCity(item.children || [], code, item);
}
})
}
findCity(json, code);
names = [...new Set(names)];
codes = [...new Set(codes)];
return { codes, names };
}
const list = getArea(cityJson, parseInt(code));
console.log(list);