[
{
\"id\": \"a\",
\"pid\": \"a\",
\"name\": \"AA\",
},
{
\"id\": \"b\",
\"pid\": \"a\",
\"name\": \"BB\",
},
{
\"id\": \"c\",
Influenced by the answer of Nina, this is my resolution just for the record.
function corrugate(data){
var root = "";
return data.reduce((t,o) => {
o.id === o.pid && (root = o.id);
t[o.id] ? t[o.id].name = o.name
: t[o.id] = {id: o.id, name: o.name};
t[o.pid] ? o.pid !== o.id ? t[o.pid].children.push(t[o.id])
: t[o.pid].children = t[o.pid].children || []
: t[o.pid] = {id: o.pid, children: [t[o.id]]};
return t;
},{})[root];
}
var data = [{ "id": "f", "pid": "b", "name": "F" },
{ "id": "e", "pid": "c", "name": "E" },
{ "id": "b", "pid": "a", "name": "B" },
{ "id": "d", "pid": "c", "name": "D" },
{ "id": "c", "pid": "b", "name": "C" },
{ "id": "a", "pid": "a", "name": "A" }
];
console.log(corrugate(data));