在我的图表中,我有三种实体。
省,区和市。
关系是市属于区,区属于省。
这是我的数据库表
区域。
id | region_name | region_parent_id
1 | Western province | null
2 | Colombo | 1
3 | Gampaha | 1
4 | Kaluthara | 1
5 | Nugegoda | 2
6 | Maharagama | 2
7 | Central province | null
8 | Kandy | 7
9 | Mathale | 7
10 | theldeniya | 8
11 | penideniya | 8
如果我得出关系,我会是这样,
西部省
科伦坡
Nugegoda
Maharagama
甘帕哈
卡卢塔拉
中央省
康提
Theldeniya
Penideniya
Mathale
我得到的数据是这样的对象数组,
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(regions.filter(e=> !e.region_parent_id ))
我可以很容易地得到像这样的省。
console.log(regions.filter(e=> !e.region_parent_id ))
但是,如何获得地区列表和城市列表?
最佳答案
尝试这个:
var parId = prompt("Enter region parent id : " ) ;
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}
]
function belong(dis) {
var getProvince = regions.find( e => e.id === dis ) ;
if ( getProvince ) {
console.log("==========" + getProvince.region_name + "==========" ) ;
regions.map( c => {if (c.region_parent_id === dis ) console.log(c.region_name + " " + c.id +" Parent:(" + c.region_parent_id +")") } )
}
}
belong( parseInt(parId) );
关于javascript - 基于id的Javascript过滤器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54016124/