具有递归关系的JavaScript过滤器

时间:2019-01-21 10:42:46

标签: javascript

我的用例就是这样。

  • 我有一个称为位置的对象数组。
  • 它包含有关省,地区和城市的信息。
  • 城市属于地区,地区属于省。
  • 如果parent_region_id null表示它是一个省。
  • 如果parent_region_id是一个省的ID,则表示它是一个区。
  • 否则它是一座城市。

我的目标是从阵列中过滤掉所有城市。 我做了一个奇怪的方法,尽管它起作用。

但是我想知道最理想的方法是什么? 这是我的工作代码。

const locations = [
{id:1,name:"Western province",parent_region_id:null},
{id:2,name:"Southern province",parent_region_id:null},
{id:3,name:"Central province",parent_region_id:null},
{id:4,name:"Colombo district",parent_region_id:1},
{id:5,name:"Galle district",parent_region_id:2},
{id:6,name:"Kandy district",parent_region_id:3},
{id:7,name:"Maharagama",parent_region_id:4},
{id:8,name:"Nugegoda",parent_region_id:4},
{id:9,name:"Peradeniya",parent_region_id:6},
]

//get the province ids first

const provinces = []

locations.forEach(e=> {
if(!e.parent_region_id){
  provinces.push(e.id)
}
})

// get all the districts then

const districts = []

locations.forEach(e=>{
  if(provinces.includes(e.parent_region_id)){
  districts.push(e.id) 
  }
})


//get cities

const cities = [];


locations.forEach(e=> 
{
  if(!districts.includes(e.id) && !provinces.includes(e.id)){
    console.log(e.name," is a city")
  }
})

2 个答案:

答案 0 :(得分:2)

使用Array#filterArray#find

20px

先删除省份的解决方案:

const locations=[{id:1,name:"Western province",parent_region_id:null},{id:2,name:"Southern province",parent_region_id:null},{id:3,name:"Central province",parent_region_id:null},{id:4,name:"Colombo district",parent_region_id:1},{id:5,name:"Galle district",parent_region_id:2},{id:6,name:"Kandy district",parent_region_id:3},{id:7,name:"Maharagama",parent_region_id:4},{id:8,name:"Nugegoda",parent_region_id:4},{id:9,name:"Peradeniya",parent_region_id:6},]

const res = locations.filter(({id, parent_region_id},i,a)=>{
  if(!parent_region_id) return false;
  const loc = a.find(l=>l.id === parent_region_id);
  return !loc.parent_region_id ? false : true;
});

console.log(res);

答案 1 :(得分:0)

如果您想使代码更简洁,更紧凑,请尝试使用filter(),如下所示:

 

const locations = [
{id:1,name:"Western province",parent_region_id:null},
{id:2,name:"Southern province",parent_region_id:null},
{id:3,name:"Central province",parent_region_id:null},
{id:4,name:"Colombo district",parent_region_id:1},
{id:5,name:"Galle district",parent_region_id:2},
{id:6,name:"Kandy district",parent_region_id:3},
{id:7,name:"Maharagama",parent_region_id:4},
{id:8,name:"Nugegoda",parent_region_id:4},
{id:9,name:"Peradeniya",parent_region_id:6},
];

const provinces = locations.filter(e => !e.parent_region_id);

const districts = locations.filter(e => provinces.some(p => p.id == e.parent_region_id));

const cities = locations.filter(e => !provinces.includes(e) && !districts.includes(e));

console.log(provinces);
console.log(districts);
console.log(cities);