js 数据遍历问题

   const arr = [
        {
          id: 1,
          name: "张三",
          children: [
            {
              id: 1.1,
              name: "张四",
              children: [{ id: 1.11, name: "张五" }]
            }
          ]
        }
      ];

已知张五id,怎么拿到张四id

已知张四id,怎么拿到张三id

阅读 2.4k
4 个回答

使用递归遍历实现:

  function findId(arr, id, pid) {
      for (let i = 0; i < arr.length; i++) {
        let item = arr[i].children
        if (arr[i].id === id) {
            prevId = pid
            break
        }
        if (item) {
            findId(item, id, arr[i].id)
        }
      }
    return prevId
  }
  console.log(findId(arr, 1.11, ''))

直接点,给代码。

function findParentId(id) {
    let arrMap = new Map();
    function patchArr(arr, pid = null) {
        arr.forEach(element => {
            arrMap.set(element.id,{ ...element, pid })
            element.children && (patchArr(element.children, element.id))
        });
    }
    patchArr(arr)
    return arrMap.get(id).pid;
}

console.log(findParentId(1.11)); // 1.1
function findChild(condition, children, parent = null) {
    for (let child of children) {
        if (condition(child)) {
            return parent;
        } else {
            if (child.children) {
                return findChild(condition, child.children, child);
            } else {
                return null;
            }
        }
    }
}

使用方式:image.png

试试我写的树操作库,一两行代码就可以实现:https://github.com/Lushenggang/js-tree-tool

// 一次性找到所有祖先节点
const path = treeTool.findPath(arr, n => n.id == 1.11)
const result = path.map(node => node.id) // [1, 1.1, 1.11]

当然,了解实现方法还是有必要的,代码实现在这篇文章中有写:
https://wintc.top/article/20
image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题