I have a flat list as shown below.
flatList = [
    {
        id: "39000000", 
        parent: null, 
        description: "Electric Systems", 
        name: "39000000"
    },
    {
        id: "39120000", 
        parent: "39000000", 
        description: "Electrical Equipment", 
        name: "39120000"
    },
    {
        id: "39121000", 
        parent: "39120000", 
        description: "Power Conditioning", 
        name: "39121000"
    },  
    {
        id: "39121011", 
        parent: "39121000", 
        description: "Uninterruptible Power Supply", 
        name: "39121011"
    }
];
Method to construct tree from flat list and store the tree in nestedList
nestedList = [];
getTree(flatList) {
    flatList.forEach(element => {
      if (!element.parent) {
        this.nestedList.push({ id: element.id, name: element.name, description: element.description, children: [] });
      } else {
        if (this.nestedList.findIndex(item => item.id === element.parent) === -1) {
          this.nestedList.push({
            id: element.id, name: element.name, description: element.description, children: [{ id: element.id, name: element.name, description: element.description, children: [] }]
          });
        } else {
          this.nestedList.find(item => item.id === element.parent).children.push(
            { id: element.id, name: element.name, description: element.description, children: [] }
          );
        }
      }
    });
  }
Output that I am getting looks like this.
nestedList = [
    {
        id: "39000000", 
        name: "39000000",  
        description: "Electric Systems", 
        children: [{
            id: "39120000", 
            name: "39120000", 
            description: "Electrical Equipment", 
            children: []}
        ]
    },
    {
        id: "39121000", 
        name: "39121000", 
        description: "Power Conditioning", 
        children: [{
                id: "39121000", 
                name: "39121000", 
                description: "Power Conditioning", 
                children: []
            },
            {
                id: "39121011", 
                name: "39121011", 
                description: "Uninterruptible Power Supply", 
                children: []
            }       
        ]
    }   
]
Desired output should be:
    nestedList = [
    {
      id: "39000000",
      name: "39000000",
      description: "Electric Systems",
      children: [{
        id: "39120000",
        name: "39120000",
        description: "Electrical Equipment",
        children: [{
          id: "39121000",
          name: "39121000",
          description: "Power Conditioning",
          children: [{
            id: "39121011",
            name: "39121011",
            description: "Uninterruptible Power Supply",
          }]
        }]
      }]
    }
  ]
Help would be appreciated.