TypeScript Implements Conversion of Flat Structure Into Tree Structure


To convert a given tiled array of Items into a tree-structured ITreeItem, you can use a recursive approach to build the tree.


Here is an example of a possible TypeScript implementation:

interface Item {
   id: string;
   name: string;
   childrenId?: string[];
   parentId?: string;

interface ITreeItem extends Item {
   children?: ITreeItem[]

function buildMenuTree(items: Item[], parentId?: string): ITreeItem[] {
   const tree: ITreeItem[] = [];

   for (const item of items) {
     if (item. parentId === parentId) {
       const treeItem: ITreeItem = {
         children: buildMenuTree(items, item.id)
       tree. push(treeItem);

   return tree;

const flatMenu: Item[] = [

     "id": "1",
     "name": 'vegetable'
     "id": "2",
     "name": 'fruit',
     "childrenId": [
     "id": "3",
     "name": 'banana',
     "parentId": "2"
     "id": "4",
     "name": 'apple',
     "parentId": "2"

const menuTree: Item[] = buildMenuTree(flatMenu);

console.log(JSON.stringify(menuTree, null, 2)); // Output the menu tree structure

Paste the code into https://www.typescriptlang.org/play to try it out.

In this example, the buildMenuTree function accepts a flat array of Item and an optional parentId parameter, and then recursively builds the tree structure. For each item, it checks if the item's parentId matches the passed parentId, and if so then adds the item to the current node's children array.

You can put the sample data you provided into a flatMenu array and then run the code and it will output a menuTree of a tree structure. Please note that this is just a sample implementation and you can adjust it as needed.