console.log("Hello world! - js.jsrun.net ");
function getAllKeysByCode(data, code) {
let result = [];
function findNode(nodeList) {
for (const node of nodeList) {
if (node.key === code) {
collectKeys(node);
} else if (node.childList.length > 0) {
findNode(node.childList);
}
}
}
function collectKeys(node) {
if (node.childList.length === 0) {
result.push(node.key);
} else {
for (const child of node.childList) {
collectKeys(child);
}
}
}
findNode(data);
return result;
}
const data = [
{
key: '820000',
value: '澳门',
childList: [
{ key: '820001', value: '花地玛堂区', childList: [] },
{ key: '820002', value: '花王堂区', childList: [] },
{ key: '820003', value: '望德堂区', childList: [] },
{ key: '820004', value: '大堂区', childList: [] },
{ key: '820005', value: '风顺堂区', childList: [] },
{ key: '820006', value: '嘉模堂区', childList: [] },
{ key: '820007', value: '路凼填海区', childList: [] },
{ key: '820008', value: '圣方济各堂区', childList: [] },
{ key: '820100', value: '澳门特别行政区', childList: [] },
],
},
{
key: '710000',
value: '台湾省',
childList: [
{
key: '710100',
value: '台北市',
childList: [
{ key: '710101', value: '北投区', childList: [] },
{ key: '710102', value: '松山区', childList: [] },
{ key: '710103', value: '大同区', childList: [] },
{ key: '710104', value: '文山区', childList: [] },
{ key: '710105', value: '信义区', childList: [] },
{ key: '710106', value: '内湖区', childList: [] },
{ key: '710107', value: '中正区', childList: [] },
{ key: '710108', value: '万华区', childList: [] },
{ key: '710109', value: '中山区', childList: [] },
{ key: '710110', value: '士林区', childList: [] },
{ key: '710111', value: '南港区', childList: [] },
{ key: '710112', value: '大安区', childList: [] },
],
},
{
key: '710400',
value: '台中市',
childList: [
{ key: '710401', value: '东区', childList: [] },
{ key: '710402', value: '新社区', childList: [] },
{ key: '710403', value: '中区', childList: [] },
{ key: '710404', value: '屯区', childList: [] },
{ key: '710405', value: '神冈区', childList: [] },
{ key: '710406', value: '沙鹿区', childList: [] },
{ key: '710407', value: '丰原区', childList: [] },
{ key: '710408', value: '大里区', childList: [] },
{ key: '710409', value: '龙井区', childList: [] },
{ key: '710410', value: '西区', childList: [] },
{ key: '710411', value: '南区', childList: [] },
{ key: '710412', value: '西屯区', childList: [] },
{ key: '710413', value: '太平区', childList: [] },
],
},
],
},
];
const result = getAllKeysByCode(data, '820001');
console.log(result);