gpt4 book ai didi

Javascript 过滤掉某个类别

转载 作者:行者123 更新时间:2023-11-28 12:57:18 28 4
gpt4 key购买 nike

我有一个对象数组。

const regions = [
{id:1,region_name:"Western province",region_parent_id:null},
{id:2,region_name:"Colombo",region_parent_id:1},
{id:3,region_name:"Gampaha",region_parent_id:1},
{id:4,region_name:"Kaluthara",region_parent_id:1},
{id:5,region_name:"Nugegoda",region_parent_id:2},
{id:6,region_name:"Maharagama",region_parent_id:2},
{id:7,region_name:"Central province",region_parent_id:null},
{id:8,region_name:"Kandy",region_parent_id:7},
{id:9,region_name:"Mathale",region_parent_id:7},
{id:10,region_name:"theldeniya",region_parent_id:8},
{id:11,region_name:"penideniya",region_parent_id:8}

]

console.log("PROVINCES",regions.filter(e=> !e.region_parent_id));

// get districts
let province_ids = []
regions.forEach(e=>{
if(!e.region_parent_id){
province_ids.push(e.id)
}
})

console.log("PROVINCE IDS",province_ids)

regions.forEach(e=>{
if(province_ids.includes(e.region_parent_id)){
console.log(e.region_name,"IS A DISTRICT")
}
})

这些对象可以分为 3 种类型。

  1. 省份
  2. 城市

关系是市属于区,区属于省。

我可以像这样轻松获得省份、地区。

您能告诉我如何获得城市吗?

最佳答案

您可以使用Array.prototype.some()像这样:

const regions = [
{id:1,region_name:"Western province",region_parent_id:null},
{id:2,region_name:"Colombo",region_parent_id:1},
{id:3,region_name:"Gampaha",region_parent_id:1},
{id:4,region_name:"Kaluthara",region_parent_id:1},
{id:5,region_name:"Nugegoda",region_parent_id:2},
{id:6,region_name:"Maharagama",region_parent_id:2},
{id:7,region_name:"Central province",region_parent_id:null},
{id:8,region_name:"Kandy",region_parent_id:7},
{id:9,region_name:"Mathale",region_parent_id:7},
{id:10,region_name:"theldeniya",region_parent_id:8},
{id:11,region_name:"penideniya",region_parent_id:8}
];

const provinces = regions.filter(r => r.region_parent_id == null);
const districts = regions.filter(r => provinces.some(p => p.id === r.region_parent_id));
const cities = regions.filter(r => districts.some(d => d.id === r.region_parent_id));

console.log("Provinces: ", provinces);
console.log("Districts: ", districts);
console.log("Cities: ", cities);

这当然不是最有效的方法,但只要您的区域列表相对较短,就不应该造成任何问题。

关于Javascript 过滤掉某个类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54140866/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com