0
我對這個問題困惑了好幾個小時。我正在使用Angular和angular-ui-tree來創建一個葉子數量未知的可編輯樹。 我需要將樹平坦化並將其轉換爲分層數組,以便將其傳遞給MongoDb。我也使用Underscore.js作爲工具將樹狀結構轉換爲分層陣列
var tree = [{
"_id": 1,
"title": "node1",
"nodes": [{
"_id": 11,
"title": "node1.1",
"nodes": [{
"_id": 111,
"title": "node1.1.1",
"children": [{
"_id": 1111,
"title": "node1.1.1.1",
"children": []
}]
}]
}, {
"_id": 12,
"title": "node1.2",
"children": []
}]
}, {
"_id": 2,
"title": "node2",
"children": [{
"id": 21,
"title": "node2.1",
"children": []
}, {
"_id": 22,
"title": "node2.2",
"children": []
}]
}, {
"_id": 3,
"title": "node3",
"children": [{
"id": 31,
"title": "node3.1",
"children": []
}]
}, {
"_id": 4,
"title": "node4",
"children": [{
"_id": 41,
"title": "node4.1",
"children": []
}]
}]
//desired output
//parentId is null for top leaf nodes, path is String made by the parents' ids
[
{ "_id": 1, "title": "node1", "parentId": null, "path" : ""},
{ "_id": 11, "title": "node1.1", "parentId": 1, "path" : ",1"},
{ "_id": 111, "title": "node1.1.1", "parentId": 11, "path" : ",1,11"},
{ "_id": 1111, "title": "node1.1.1.1", "parentId": 111, "path" : ",1,11,111"},
{ "_id": 12, "title": "node1.1", "parentId": 1, "path" : ",1"},
{ "_id": 2, "title": "node2", "parentId": null, "path" : ""},
{ "_id": 21, "title": "node2.1", "parentId": 2, "path" : ",2"},
{ "_id": 3, "title": "node3", "parentId": null, "path" : ""},
{ "_id": 31, "title": "node3.1", "parentId": 3, "path" : ",3"},
{ "_id": 4, "title": "node4", "parentId": null, "path" : ""},
{ "_id": 41, "title": "node4.1", "parentId": 4, "path" : ",4"},
]