我有以下數據結構:遍歷層次在Javascript
{
"data":[
{
"id":1,
"name":"EU Group",
"parent_id":null,
"children":[
{
"id":2,
"name":"EMEA Branch",
"parent_id":1,
"children":[
{
"id":5,
"name":"UK",
"parent_id":2,
"lr":","
},
{
"id":6,
"name":"France",
"parent_id":2,
"lr":","
},
{
"id":7,
"name":"Germany",
"parent_id":2,
"lr":","
},
{
"id":8,
"name":"Spain",
"parent_id":2,
"lr":","
},
{
"id":9,
"name":"Finland",
"parent_id":2,
"lr":","
},
{
"id":10,
"name":"Hungary",
"parent_id":2,
"lr":","
},
{
"id":11,
"name":"Poland",
"parent_id":2,
"children":[
{
"id":25,
"name":"Romania",
"parent_id":11,
"lr":","
}
],
"lr":","
},
{
"id":12,
"name":"Sweden",
"parent_id":2,
"lr":","
},
{
"id":16,
"name":"Italy",
"parent_id":2,
"lr":","
},
{
"id":17,
"name":"Czech",
"parent_id":2,
"lr":","
},
{
"id":18,
"name":"Denmark",
"parent_id":2,
"lr":","
},
{
"id":19,
"name":"Rest of the world",
"parent_id":2,
"lr":","
},
{
"id":36,
"name":"Middle East",
"parent_id":2,
"children":[
{
"id":21,
"name":"Russia",
"parent_id":36,
"lr":","
}
],
"lr":","
},
{
"id":38,
"name":"Africa",
"parent_id":2,
"children":[
{
"id":49,
"name":"Algeria",
"parent_id":38,
"lr":","
},
{
"id":50,
"name":"Morocco",
"parent_id":38,
"lr":","
}
],
"lr":","
},
{
"id":48,
"name":"Belgium",
"parent_id":2,
"lr":","
}
],
"lr":","
},
{
"id":45,
"name":"International Branch",
"parent_id":1,
"lr":","
},
{
"id":46,
"name":"APAC Branch",
"parent_id":1,
"children":[
{
"id":51,
"name":"Singapore",
"parent_id":46,
"lr":","
},
{
"id":52,
"name":"China",
"parent_id":46,
"lr":","
},
{
"id":53,
"name":"Vietnam",
"parent_id":46,
"lr":","
},
{
"id":54,
"name":"Indonesia",
"parent_id":46,
"lr":","
},
{
"id":55,
"name":"India",
"parent_id":46,
"lr":","
},
{
"id":56,
"name":"Malaysia",
"parent_id":46,
"lr":","
}
],
"lr":","
}
],
"lr":","
}
]
}
我想要使用此功能,我創建了它遍歷:
buildHierarchy(item) {
zone.children.forEach((child) => {
this.buildHierarchy(child);
})
}
這是在所謂的進一步下跌我的渲染功能:
render() {
...
if (zones[0]) {
this.buildHierarchy(zones);
...
}
...
}
但是,當它碰到一個沒有孩子的物品時會中斷。我怎樣才能使這個工作?
只需添加,如果要檢查是否有孩子嗎? – Leon
你應該檢查zone.children是否爲空? –
@Leon,但它會跳出循環,並可能錯過其他可能有或沒有孩子的物品。 – imperium2335