Nemanja Andric
Nemanja Andric

Reputation: 665

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

Upvotes: 0

Views: 897

Answers (2)

ALGDB
ALGDB

Reputation: 680

Whitout knowledge of the template of the data is very hard to know if this will work,

anyway you can try this in case you have any error we can adjust it

export const deepIdSearch = (obj: any, strId: string = 'id'): any => {
  let copy: any;

  // Handle the 3 simple types, and null or undefined
  if (null == obj || 'object' != typeof obj || obj instanceof Date) return;

  // Handle Array
  if (obj instanceof Array) {
    for (var i = 0, len = obj.length; i < len; i++) {
     copy = deepIdSearch(obj[i]);
    }
    return copy;
  }

  // Handle Object
  if (obj instanceof Object) {
    copy = {};
    for (let attr in obj) {
      if (obj.hasOwnProperty(attr)) attr === strId ? (copy = obj) : deepIdSearch(obj[attr]);
    }
    return copy;
  }

  throw new Error('Unable to Find');
};

Upvotes: 1

Newbie
Newbie

Reputation: 4819

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');
}

Upvotes: 1

Related Questions