在树状数组总,找到某个field字段为value值的某个对象节点

在树状数组总,找到某个field字段为value值的某个对象节点,使用递归

export const findTreeItemBy = (
  nodes: Array<any>,
  value: any,
  fieldMap: { value: string; children: string } = { value: "id", children: "children" },
) => {
  if (!Array.isArray(nodes)) return
  for (const node of nodes) {
    if (node[fieldMap.value] == value) {
      return node
    }
    if (node[fieldMap.children] && node[fieldMap.children].length) {
      const res = findTreeItemBy(node[fieldMap.children], value, {
        value: fieldMap.value,
        children: fieldMap.children,
      })
      if (res) return res
    }
  }
}

你可能感兴趣的:(算法,数据结构,javascript)