user944513 February 2016

how to add parents name in an object (got parent count )

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/

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']},
}

Answers


Marc February 2016

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]; 
});


georg February 2016

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]:

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 ]

Post Status

Asked in February 2016
Viewed 2,652 times
Voted 12
Answered 2 times

Search




Leave an answer