javascript 数组转tree结构

数组数据
var list = [
  {id:1,pid:0,name:'一级'},
  {id:2,pid:1,name:'一级1'},
  {id:3,pid:1,name:'一级2'},
  {id:4,pid:2,name:'一级1-1'}
]

 

核心代码:

// 数组转tree
function
composeTree(list = []) { const data = JSON.parse(JSON.stringify(list)) // 浅拷贝不改变源数据 const result = [] if (!Array.isArray(data)) { return result } data.forEach(item => { delete item.children }) const map = {} data.forEach(item => { map[item.id] = item }) data.forEach(item => { const parent = map[item.pid] if (parent) { (parent.children || (parent.children = [])).push(item) } else { result.push(item) } }) return result }

 调用方法:

let tree = composeTree(list)

console.log(tree) // [{"id":1,"pid":0,"name":"一级","children":[{"id":2,"pid":1,"name":"一级1","children":[{"id":4,"pid":2,"name":"一级1-1"}]},{"id":3,"pid":1,"name":"一级2"}]}]

通过以上代码转换后的数据可以直接用于 各种树形组件 如 element

posted @ 2019-07-05 09:36  leeseett  阅读(971)  评论(0编辑  收藏  举报