I would like to create Parent Child array how it’s possible
i create listCategory function but i don’t know how to make parent child array in listCategory function
here is my code.
type CategoryId = Nat32;
type Category = {
id : CategoryId;
name : Text;
parent_id : Int;
sort_order : Int;
};
type ParentChildCategory = {
id : CategoryId;
name : Text;
parent_id : Int;
children : [child];
sort_order : Int;
};
type child = {
id : CategoryId;
name : Text;
parent_id : Int;
sort_order : Int;
};
private stable var categoryEntries : [(CategoryId, Category)] = [];
var categoryHashMap = HashMap.HashMap<CategoryId, Category>(
10,
func(x, y) { x == y },
func(x) { x },
);
stable var lastCategoryId : Nat32 = 0;
private func nextCategoryId() : Nat32 {
lastCategoryId += 1;
lastCategoryId;
};
public func addNewCategory(id : Nat32, category : Category) {
let id = nextCategoryId();
categoryHashMap.put(id, addCategory(id, category));
};
func addCategory(categoryId : Nat32, category : Category) : Category {
{
id = categoryId;
name = category.name;
parent_id = category.parent_id;
description = category.description;
status = category.status;
sort_order = category.sort_order;
};
};
public func listCategory() : async [Category] {
let buff : Buffer.Buffer<Category> = Buffer.Buffer(10);
for (e in categoryHashMap.vals()) {
Debug.print(debug_show (e));
buff.add(e);
};
buff.toArray();
};
I want this kind of output.
[
{
name: "name",
id:"id",
parent_id : "parent_id",
sort_order : "sort_order",
"children": [
{
name: "name",
id:"id",
parent_id : "parent_id",
sort_order : "sort_order",
"children" : [
{
name: "name",
id:"id",
parent_id : "parent_id",
sort_order : "sort_order",
}
]
},
{
name: "name",
id:"id",
parent_id : "parent_id",
sort_order : "sort_order",
"children" : [
{
name: "name",
id:"id",
parent_id : "parent_id",
sort_order : "sort_order",
},
{
name: "name",
id:"id",
parent_id : "parent_id",
sort_order : "sort_order",
}
]
}
]
}
]