多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
>[success] # 小的案例 ~~~ 1.现有api返回数据[ {province:'⼴东省',city:'⼴州市',district:'天河区'}, {province:'⼴东省',city:'⼴州市',district:'⽩云区'}, {province:'⼴东省',city:'东莞市',district:'常平镇'}] 请问如何在最短时间内处理成[{ name: '⼴东省', children: [ { name: '⼴州 市', children: [{name: '天河区'},{name:'⽩云区'}] }, { name: '东莞市', children: [{name: '常平镇'}] }, ]}] ~~~ >[danger] ##### 不完善的解决方案 ~~~ 1.下面代码不太完善只是完成了思路,整个代码用了组合和工厂模式实现 ~~~ ~~~ class Root{ constructor(name){ this.name = name this.children = [] this.parent = null } add(file){ file.parent = this this.children.push(file) } } class DistrictLeaf{ constructor(name){ this.name = name this.parent = null } add(file){ throw new Error( '区下面不能添加' ); } } class Factory{ obj = {} creat(name){ if(this.obj[name]){ return this.obj[name] }else{ return this.obj[name] = new Root(name) } } } let ccc = [ {province:'⼴东省',city:'⼴州市',district:'天河区'}, {province:'⼴东省',city:'⼴州市',district:'⽩云区'}, {province:'⼴东省',city:'东莞市',district:'常平镇'}] // const provinceRoot = new Root('⼴东省') const provinceRoot = new Factory() const districtRoot = new Factory() ccc.forEach(item =>{ const province = provinceRoot.creat(item.province) const district = new DistrictLeaf(item.district) if(!Reflect.has(districtRoot.obj,item.city)){ const city = districtRoot.creat(item.city) province.add(city) city.add(district) } }) console.log(provinceRoot.obj) ~~~