我正在嘗試找出一種方法來過濾掉陣列中的頂級分層元素,其中每個物件可能與陣列的其他元素具有父子層次結構。這是陣列的樣子:
[
{
"Code": "1A",
"name": "Western Europe",
"hierarchy": "World/",
},
{
"Code": "AT",
"name": "Austria",
"hierarchy": "World/ Western Europe/"
},
{
"Code": "NL",
"name": "Netherlands",
"hierarchy": "World/ Western Europe/"
}
]
對于此示例,輸出應該只是第一個物件,因為西歐是奧地利和荷蘭的父級。
[
{
"Code": "WO",
"name": "World",
"hierarchy": "",
},
{
"Code": "NA",
"name": "North America",
"hierarchy": "World/",
},
{
"Code": "NL",
"name": "Netherlands",
"hierarchy": "World/ Western Europe/"
}
]
這里的輸出將是 World,因為 World 是最高層次結構。
[
{
"Code": "1A",
"name": "Western Europe",
"hierarchy": "World/",
},
{
"Code": "NA",
"name": "North America",
"hierarchy": "World/",
},
{
"Code": "US",
"name": "United States",
"hierarchy": "World/ North America/",
},
{
"Code": "NL",
"name": "Netherlands",
"hierarchy": "World/ Western Europe/"
},
{
"Code": "RS",
"name": "Russia",
"hierarchy": "World/ Eastern Europe/",
},
]
在這里,輸出應該是西歐、北美和俄羅斯(因為我們在串列中沒有東歐,所以俄羅斯處于其層次結構的頂部)。所以,我們必須得到頂層的分層元素。我有一個函式可以傳遞代碼并獲取層次結構:
getParentChildHierarchy(string Code) { //這里有一些代碼 }
Input: AT
Output: WO>1A>AT
您能提出解決此問題的最佳方法嗎?
uj5u.com熱心網友回復:
一種方法是創建資料集中所有路徑的集合,即與 的連接hierarchy(name遵循與斜線和間距相同的格式)。然后檢查該集合中hierarchy實際存在哪些節點(參考父節點)。如果沒有,它在資料集中沒有父節點:
const data = [
{
"Code": "1A",
"name": "Western Europe",
"hierarchy": "World/",
}, {
"Code": "NA",
"name": "North America",
"hierarchy": "World/",
}, {
"Code": "US",
"name": "United States",
"hierarchy": "World/ North America/",
}, {
"Code": "NL",
"name": "Netherlands",
"hierarchy": "World/ Western Europe/"
}, {
"Code": "RS",
"name": "Russia",
"hierarchy": "World/ Eastern Europe/",
},
];
const keys = new Set(data.map(o => o.hierarchy " " o.name "/"));
const topLevel = data.filter(o => !keys.has(o.hierarchy));
console.log(topLevel);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520461.html
上一篇:計算到點P的k個最近點的快速方法
