I am looking to restructure my JavaScript object into a hierarchical tree pattern object. Here is my current object:
let input = [
{'id':1 ,'pid' : 0},
{'id':2 ,'pid' : 1},
{'id':3 ,'pid' : 2},
{'id':4 ,'pid' : 2},
{'id':5 ,'pid' : 3},
{'id':6 ,'pid' : 3},
{'id':7 ,'pid' : 4},
{'id':8 ,'pid' : 4},
{'id':9 ,'pid' : 4}
];
I came across this helpful snippet online, which works well (unfortunately, I forgot the source, but thank you anyway)
let input = [
{'id':1 ,'pid' : 0},
{'id':2 ,'pid' : 1},
{'id':3 ,'pid' : 2},
{'id':4 ,'pid' : 2},
{'id':5 ,'pid' : 3},
{'id':6 ,'pid' : 3},
{'id':7 ,'pid' : 4},
{'id':8 ,'pid' : 4},
{'id':9 ,'pid' : 4}
];
let register = {};
let output = {};
for (let el of input) {
el = Object.assign({}, el);
register[el.id] = el;
if (!el.pid) {
output[el.id] = el;
} else {
register[el.pid][el.id] = el
}
delete el.pid;
delete el.id
}
document.body.innerHTML = "<pre>" + (JSON.stringify(output, undefined, 2))
However, when I changed the PID value from {'id':4 ,'pid' : 2}
to {'id':4 ,'pid' : 9}
, an issue arose with register[el.pid]
being undefined.
I need assistance in resolving this issue, thank you in advance.