JS-如何在JSON树形结构中找到子节点的父级路径

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS-如何在JSON树形结构中找到子节点的父级路径</title>
<script>
const data = [
    {
        id:1,
        pid:'a',
        text:1,
        children:[{
            id:2,
            pid:'b',
            text:2,
            children:[{
                id:3,
                pid:'c',
                text:3,
                children:[{
                    id:4,
                    pid:'d',
                    text:3,
                    children:[]
                },
                         {
                    id:5,
                    pid:'d2',
                    text:3,
                    children:[]
                }]
            }]
        }]
    }
]
    
function findIndexArray (data, id, indexArray) {
  let arr = Array.from(indexArray)
  for (let i = 0, len = data.length; i < len; i++) {
    arr.push(data[i].pid)
    if (data[i].id === id) {
      return arr
    }
    let children = data[i].children
    if (children && children.length) {
      let result = findIndexArray(children, id, arr)
      if (result) return result
    }
    arr.pop()
  }
  return false
}

console.log(findIndexArray(data, 5, [])) // [0, 0, 0]
</script>
</head>
<body>

</body>
</html>

通过修改代码,也可以实现取到路径上的值。

猜你喜欢

转载自blog.csdn.net/kukudelaomao/article/details/88599307
今日推荐