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 –