var nodes = [
{id: 1, pid: 0, name: "kpittu"},
{id: 2, pid: 0, name: "news"},
{id: 3, pid: 0, name: "menu"},
{id: 4, pid: 3, name: "node"},
{id: 5, pid: 4, name: "subnode"},
{id: 6, pid: 1, name: "cace"}
];
const helper = nodes.reduce((h, o) => (h[o.id] = Object.assign({}, o), h), Object.create(null));
const tree = nodes.reduce((t, node) => {
const current = helper[node.id];
if(current.pid === 0) { // if it doesn't have a parent push to root
t.push(current);
} else {
helper[node.pid].children || (helper[node.pid].children = []) // add the children array to the parent, if it doesn't exist
helper[node.pid].children.push(current); // push the current item to the parent children array
}
return t;
}, []);
console.log(tree);