let arr = [
{ areaId: 43, areaLevel: 0, areaName: "湖南" },
{ areaId: 42, areaLevel: 0, areaName: "湖北" },
{ areaId: 4201, areaLevel: 1, areaName: "十堰" },
{ areaId: 420101, areaLevel: 2, areaName: "高新区" },
{ areaId: 4301, areaLevel: 1, areaName: '长沙' },
{ areaId: 430102, areaLevel: 2, areaName: '芙蓉' },
{ areaId: 430103, areaLevel: 2, areaName: '天心' },
{ areaId: 4303, areaLevel: 1, areaName: '湘潭' },
{ areaId: 430302, areaLevel: 2, areaName: '雨湖' },
{ areaId: 430304, areaLevel: 2, areaName: '岳塘' }
];
let arr_re = [
{ areaId: 430102, province: "湖南", city: "长沙", area: "芙蓉" },
{ areaId: 430103, province: "湖南", city: "长沙", area: "天心" },
{ areaId: 430302, province: "湖南", city: "湘潭", area: "雨湖" },
{ areaId: 430304, province: "湖南", city: "湘潭", area: "岳塘" },
];
// 思路一:先筛选出省、市的数据存起来,再拿区的id和省、市id进行包含关系匹配,得到结果
// const province_level = 0, city_level = 1, area_level = 2;
// let provinceList = [], cityList = [], re = [];
// arr.forEach(item => {
// item.areaId = item.areaId.toString();
// if (item.areaLevel === province_level) {
// if (!provinceList.find(p => p.areaId === item.areaId)) {
// provinceList.push({ areaId: item.areaId, province: item.areaName });
// return;
// }
// }
// if (item.areaLevel === city_level) {
// if (!cityList.find(c => c.areaId === item.areaId)) {
// cityList.push({ areaId: item.areaId, city: item.areaName });
// return;
// }
// }
// if (item.areaLevel === area_level) {
// let { province } = provinceList.find(p => item.areaId.indexOf(p.areaId) !== -1);
// let { city } = cityList.find(c => item.areaId.indexOf(c.areaId) !== -1);
// re.push({
// areaId: item.areaId,
// province,
// city,
// area: item.areaName
// });
// }
// })
// console.log(re)
// 思路二:先转换成{ [areaId]: areaName }的格式,再遍历区,直接通过id截取赋值省、市数据
let areanames = arr.reduce((o, item) => {
o[item.areaId] = item.areaName;
return o;
}, {})
// let areanames = arr.reduce((o, item) =>
// ((o[item.areaId] = item.areaName), o), {}
// )
console.log(areanames)
let re = arr.filter(i => i.areaLevel == 2).map(i => {
let areaId = i.areaId
return {
areaId: areaId,
province: areanames[String(areaId).slice(0, 2)] || '',
city: areanames[String(areaId).slice(0, 4)] || '',
area: i.areaName
}
})
// console.log(re);
// 两种思路都要依赖id包关系来筛选,第二种代码更少
console