Convert a flat array with parent child mapping to a nested tree.
npm i build-tree --save
import { buildTree } from "build-tree";
const data = [
{
"id": "1",
"name": "Grocery",
"parent": null
},
{
"id": "2",
"name": "Fresh",
"parent": null
},
{
"id": "8",
"name": "Imported Fruits",
"parent": {
"id": "6"
}
},
{
"id": "9",
"name": "Local Fruits",
"parent": {
"id": "6"
}
},
{
"id": "6",
"name": "Fruits",
"parent": {
"id": "2"
}
}
];
const tree = buildTree(data, "id", "parent.id");
[
{
"id": "1",
"name": "Grocery",
"parent": null
},
{
"id": "2",
"name": "Fresh",
"parent": null,
"children": [
{
"id": "6",
"name": "Fruits",
"parent": {
"id": "2"
},
"children": [
{
"id": "8",
"name": "Imported Fruits",
"parent": {
"id": "6"
}
},
{
"id": "9",
"name": "Local Fruits",
"parent": {
"id": "6"
}
}
]
}
]
}
]