javascripttypescripttreeviewdirty-data

Find item by ID in treeview node list


Does anyone have an idea how to write a recursive method to find item by id within a treeview node list like this:

enter image description here

This data is direct binded to treeview like this

enter image description here

So I need to find item by id, and update with new values


Solution

  • Assumptions

    Assuming your node structure being:

    interface Item {
      id: string;
      [K: string]: any;
    }
    
    interface Node {
      children: Node[];
      connectionTypeId: number;
      item: Item;
    }
    

    Search

    This is a DFS (Depth First Search) on your structure (returns undefined if nothing is found):

    function findNodeById(list: Node[], id: string): Node | undefined {
      for (const n of list) {
        const res = n.item.id === id ? n : findNodeById(n.children, id);
        if (res) return res;
      }
    }
    

    This is a BFS (Breadth First Search):

    function findNodeById(list: Node[], id: string): Node | undefined {
      for (const n of list) {
        if (n.item.id === id) return n;
      }
      for (const n of list) {
        const res = findNodeById(n.children, id);
        if (res) return res;
      }
    }
    

    Update

    An update can be performed directly on the retrieved node

    const node: Node = findNodeById(list, 'f2ef4ced74448d0da8d109caf75a1073');
    if (node) {
      node.item.name = 'A new name';
      console.log('Updated');
    } else {
      console.warn('Id not found');
    }