I am trying to make a object in which it property have parent count and parent names. I am able to count the parents ..But I want to add the parent name in my code.. Here is my code https://jsfiddle.net/ood2ezvz/11/
我正在尝试创建一个对象,其中属性具有父计数和父名称。我能算出父母..但我想在我的代码中添加父名。这是我的代码https://jsfiddle.net/ood2ezvz/11/
Code
function getParentCount(nodes) {
var parent = {}, o = {};
nodes.forEach(function (n) {
parent[n.node_from] = parent[n.node_from] || [];
n.children.forEach(function (a) {
parent[a.node_to] = parent[a.node_to] || [];
parent[a.node_to].push(n.node_from);
});
});
Object.keys(parent).forEach(function (k) { o[k] = parent[k].length; });
return o;
}
my output
{11: 0, 12: 1, 13: 1, 14: 1, 15: 2, 16: 1, 17: 1, 18: 1, 19: 1}
Expected out put
期待出局
{
11:{count:0,parent:[]},
12:{count:1,parent:['11']},
13:{count:1,parent:['12']},
14:{count:1,parent:['13']},
15:{count:2,parent:['13','14']},
16:{count:1,parent:['15']},
17:{count:1,parent:['15']},
18:{count:1,parent:['15']},
19:{count:1,parent:['18']},
}
2 个解决方案
#1
0
Try to replace :
尝试替换:
Object.keys(parent).forEach(function (k) { o[k] = parent[k].length; });
By :
Object.keys(parent).forEach(function (k) {
o[k] = {};
o[k]['count'] = parent[k].length;
o[k]['parent'] = parent[k];
});
#2
0
I'd suggest converting your structure to something more usable. Since it seems to be a directed graph, a natural representation will be the list of pairs [from, to]
:
我建议将你的结构转换成更有用的东西。由于它似乎是有向图,因此自然表示将是[from,to]对的列表:
graph = []
node.forEach(n =>
n.children.forEach(c =>
graph.push([n.node_from, c.node_to])
)
)
Now you can easily find preceding and following nodes for every given node:
现在,您可以轻松找到每个给定节点的前后节点:
nodes_from = n => graph.filter(v => v[0] === n).map(v => v[1])
console.log(nodes_from(15)) // [ 16, 17, 18 ]
nodes_to = n => graph.filter(v => v[1] === n).map(v => v[0])
console.log(nodes_to(15)) // [ 13, 14 ]
#1
0
Try to replace :
尝试替换:
Object.keys(parent).forEach(function (k) { o[k] = parent[k].length; });
By :
Object.keys(parent).forEach(function (k) {
o[k] = {};
o[k]['count'] = parent[k].length;
o[k]['parent'] = parent[k];
});
#2
0
I'd suggest converting your structure to something more usable. Since it seems to be a directed graph, a natural representation will be the list of pairs [from, to]
:
我建议将你的结构转换成更有用的东西。由于它似乎是有向图,因此自然表示将是[from,to]对的列表:
graph = []
node.forEach(n =>
n.children.forEach(c =>
graph.push([n.node_from, c.node_to])
)
)
Now you can easily find preceding and following nodes for every given node:
现在,您可以轻松找到每个给定节点的前后节点:
nodes_from = n => graph.filter(v => v[0] === n).map(v => v[1])
console.log(nodes_from(15)) // [ 16, 17, 18 ]
nodes_to = n => graph.filter(v => v[1] === n).map(v => v[0])
console.log(nodes_to(15)) // [ 13, 14 ]