0
我想將具有多個路徑的倍數數組轉換爲一個平面數組的兒童。這樣做的最好方法是什麼?我嘗試使用對象引用來創建它,但它創建了一個無限循環。我可以用其他方式做到這一點嗎?將多個路徑轉換爲一個兒童數組Javascript
感謝您的幫助
這是輸入(因爲有需要結合多個路徑,也有認爲是相同的多個節點例如A到B發生兩次。):
arry = [
[
{"title":"abc", "from":"", "current": "A", "count": 1},
{"title":"abc", "from":"A", "current": "B", "count": 3},
{"title":"abc", "from":"B", "current": "C", "count": 4},
{"title":"abc", "from":"C", "current": "D", "count": 1},
],
[
{"title":"abc", "from":"", "current": "A", "count": 1},
{"title":"abc", "from":"A", "current": "B", "count": 1},
{"title":"abc", "from":"B", "current": "D", "count": 1},
],
[
{"title":"abc", "from":"", "current": "A", "count": 1},
{"title":"abc", "from":"A", "current": "J", "count": 1},
{"title":"abc", "from":"J", "current": "C", "count": 2},
{"title":"abc", "from":"C", "current": "D", "count": 3},
],
[
{"title":"abc", "from":"", "current": "A", "count": 1},
{"title":"abc", "from":"A", "current": "B", "count": 3},
{"title":"abc", "from":"B", "current": "F", "count": 1},
{"title":"abc", "from":"F", "current": "D", "count": 1},
],
//THIS COULD BE INFINITE
]//for testing
所需的輸出
{
"title": "A",
"count": 1,
"children": [
{
"value": "B",
"count": 4, //The count is sum of the nodes A->B = 3 and C->B 1
"children": [
{
"value": "C",
"count": 6,
"children": [...]
},
{
"value": "D" ,
"count": 6,
"children": [...]
},
{
"value": "F" ,
"count": 6,
"children": [...]
}
],
{
"value": "C" ,
"count": 6,
"children": [...]
},
{
"value": "J" ,
"count": 6,
"children": [...]
},
]
..
}
這是我到目前爲止有:
getTreeData(){
var map = {}, node, roots = [];
for (var i = data.nodes.length - 1; i >= 0; i--) {
for (var j = data.nodes[i].length - 1; j >=0 ; j --) {
node = data.nodes[i][j];
node.children = [];
if(!(data.nodes[i][j].current in map)){
map[data.nodes[i][j].current] = node; // use map to look-up the parents
}else{
node = map[data.nodes[i][j].current]
}
if (node.from != null && node.from !== "") {
// if(map[node.from] != null && !(data.nodes[i][j].current in map[data.nodes[i][j].from].children)){
// console.log()
if(map[node.from] != null && ! map[data.nodes[i][j].from].children.some(function (el) { return el.current === data.nodes[i][j].current; })){
map[data.nodes[i][j].from].children.push(node);
// map[data.nodes[i][j].from].children[data.nodes[i][j].current] = node;
}
} else if(roots.length <= 0){
roots.push(node);
}
}
}
return roots;
}
@happymacarts我剛剛更新的問題。謝謝 –
我不明白//計數是節點A-> B = 3和C-> B1的總和 – gr3g
@ gr3g計數是所有不重複計數的總和。所以在上面的例子中,B的數量是任何節點遍歷B的所有時間。因此A到B的計數爲3加上C到B的計數爲1 –