[英]Search in JSON Tree structure preserving Structure
我有一個像下面這樣的樹結構,
{
uid: 1,
children: [
{
uid: 2
},
{
uid: 3,
children: [
{
uid: 4
},
{
uid: 5,
children: [
{
uid: 6
}
]
},
{
uid: 7
}
]
}
]
}
現在,我想通過 uid 搜索樹結構,需要 output 作為樹結構(即與其父母一起,但沒有兄弟姐妹)
例如,如果我搜索“uid: 4”的樹結構,output 結果應該如下所示,
{
uid: 1,
children: [
{
uid: 3
children: [
{
uid: 4
}
]
}
]
}
我嘗試了遞歸,但未能與父母一起獲取匹配的元素
在 UI 中的嵌套 json 數據中實現搜索時,我想出了一種解決問題的方法。 讓我知道這是否有幫助,或者您還需要其他東西。
如果必須顯示或不顯示節點,此算法將執行搜索並遞歸更新。 如果一個節點與查詢匹配,那么它的子節點也應該是可見的。 回溯時,算法檢查節點的任何子節點是否可見,當前節點也將可見。
執行結束時,節點將具有displayNode屬性
- true 表示它應該是可見的
- false 表示應該隱藏
// Assuming this object won't contain duplicates
// 'displayNode' property, either true or false, indicating if the node should be visible
// show the node if 'displayNode' is true
// else hide
// main method
function search(obj, id) {
if (obj.children && obj.children.length > 0) {
for (let i = 0; i < obj.children.length; i++) {
const child = obj.children[i];
search(child, id);
}
}
if (obj.uid === id) {
obj['displayNode'] = true;
// recursively update the children
// if a node is true, then all it's children should also be visible
updateObj(obj);
} else {
obj['displayNode'] = false;
// if any children of this node has 'displayNode' true then this should also be visible
// to complete the path
if (obj.children && obj.children.length > 0) {
if (obj.children.find(y => y.displayNode) !== undefined) {
obj['displayNode'] = true;
}
}
}
}
// update children recursivly
function updateObj(obj) {
obj['displayNode'] = true;
if (obj.children && obj.children.length > 0) {
for (let i = 0; i < obj.children.length; i++) {
updateObj(obj.children[i]);
}
}
}
// call method
search(obj, 4);
console.log(obj);
假設原始JSON樹沒有重復項,並且假設JSON樹並不總是包含順序的uid,並且假設您只想要直接祖先線,則最好使用深度優先搜索( https://www.tutorialspoint。 com / Depth-first-search-traversal-in-Javascript )。 您還需要跟蹤當前的祖先直線,以防下一個值與您要搜索的那個相匹配。 然后,您可以返回完整的直線。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.