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 @   chenjinbang  阅读(292)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示