在树视图节点列表中按 ID 查找项目

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:

This data is direct binded to treeview like this

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

假设

假设您的节点结构是:

interface Item {
  id: string;
  [K: string]: any;
}

interface Node {
  children: Node[];
  connectionTypeId: number;
  item: Item;
}

搜索

这是对你的结构的 DFS(深度优先搜索)(returns undefined 如果没有找到):

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

这是 BFS(广度优先搜索):

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

更新

可以直接在检索到的节点上执行更新

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

如果不了解数据模板,很难知道这是否可行,

无论如何你可以试试这个,如果你有任何错误我们可以调整它

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