js树状结构数据处理

使用了两个for循环,为了方便理解,可以理解为父亲找儿子,把儿子写入家族谱
// pid:父id,为0是最顶级数据,其他则对应每项的id,即父.id = 子.pid,则父.children = 子

interface Tree {

  id: number

  pid: number

  name: string

}

 

let trees: Tree[] = [
  { id: 1, pid: 0, name: '广东省' },
  { id: 2, pid: 0, name: '上海市' },
  { id: 3, pid: 0, name: '福建省' },
  { id: 4, pid: 1, name: '深圳市' },
  { id: 5, pid: 1, name: '珠海市' },
  { id: 6, pid: 2, name: '上海市' },
  { id: 7, pid: 3, name: '厦门市' },
  { id: 8, pid: 1, name: '广州市' },
  { id: 9, pid: 8, name: '天河区' },
  { id: 10, pid: 4, name: '南山区' },
  { id: 11, pid: 4, name: '福田区' }
]

/**
 * 处理树状数据函数
 * @param data 原始树状数据
 * @return 处理后的树状数据
 */
function getTrees(data: Tree[]) {
  // 父亲找儿子,把儿子写入家族谱
  data.forEach((v: Tree) => {
    // v:儿子
    arr.forEach((v1: Tree) => {
      // v1:父亲
      if (v1.id === v.pid) {
        // 父亲找到儿子了,就添加到children
        if (!v1.children) v1.children = []
        v1.children.push(v)
      }
    })
  })
  return data
}
let newTrees = getTrees(trees)

let newArr = newTrees.filter((v) => v.pid === 0) // 筛选pid为0的数据,因为pid不为0的数据已经在pid为0的数据的子结构里面了
console.log(newArr)

 

html效果如下:

 

 

posted @ 2023-02-20 11:50  chenjinbang  阅读(252)  评论(0编辑  收藏  举报