4
4
4kuper2019-02-26 15:55:13
JavaScript
4kuper, 2019-02-26 15:55:13

How to create tree structure from adjacency list?

spoiler
[
{
"SEQNR": 1,
"LEVEL": 1,
"OTYPE": "O",
"OBJID": 80100000,
"STEXT": "Предприятие",
"PDOWN": 2,
"VCOUNT": 6,
"PNEXT": 0,
"PUP": 0,
"PPREV": 0,
"PHONS": "",
"MOBNM": "",
"EMAIL": "",
"ADDRESS": ""
},
{
"SEQNR": 2,
"LEVEL": 2,
"OTYPE": "O",
"OBJID": 9999999,
"STEXT": "управление",
"PDOWN": 8,
"VCOUNT": 53,
"PNEXT": 3,
"PUP": 1,
"PPREV": 0,
"PHONS": "",
"MOBNM": "",
"EMAIL": "",
"ADDRESS": ""
},
{
"SEQNR": 8,
"LEVEL": 3,
"OTYPE": "O",
"OBJID": 5555555555,
"STEXT": "Текст",
"PDOWN": 116,
"VCOUNT": 34,
"PNEXT": 9,
"PUP": 2,
"PPREV": 0,
"PHONS": "",
"MOBNM": "",
"EMAIL": "",
"ADDRESS": ""
},
{
"SEQNR": 116,
"LEVEL": 4,
"OTYPE": "S",
"OBJID": 80315918,
"STEXT": "Программист",
"PDOWN": 1077,
"VCOUNT": 1,
"PNEXT": 117,
"PUP": 8,
"PPREV": 0,
"PHONS": "9379992",
"MOBNM": "",
"EMAIL": "",
"ADDRESS": "Адрес"
},
{
"SEQNR": 1077,
"LEVEL": 5,
"OTYPE": "P",
"OBJID": "11111111",
"STEXT": "вася пупкин",
"PDOWN": 0,
"VCOUNT": 0,
"PNEXT": 0,
"PUP": 116,
"PPREV": 0,
"PHONS": "",
"MOBNM": "",
"EMAIL": "[email protected]",
"ADDRESS": ""
} ]

There is json, it needs to be made tree-like, there are signs by which it is determined how many dependencies are in the branch.
function list_to_tree(list) {
    var map = {}, node, roots = [], i;
    for (i = 0; i < list.length; i += 1) {
        map[list[i].OBJID] = i; // initialize the map
        list[i].PNEXT = []; // initialize the children
    }
    for (i = 0; i < list.length; i += 1) {
        node = list[i];
        if (node.PUPId !== "0") {
            // if you have dangling branches check that map[node.parentId] exists
            list[map[node.PUPId]].PNEXT.push(node);
        } else {
            roots.push(node);
        }
    }
    return roots;
}

I tried to do this but it does not work, help me tell me where I'm wrong. thanks for any tips

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Somewhere Intech, 2019-02-26
@john36allTa

I didn't find PUPID in the structure (spoiler == source?)

function list_to_tree(list) {
  return list.map( (v,i,a) =>{
    v.OBJID = i; // оно надо?
    v.PNEXT = []; // у нодов тоже должно быть?
    if (v.PUPID && v.PUPID > 0) a[v.PUPID].PNEXT.push(v);
    else return v;
  }).filter(v=>v);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question