数据处理——数组转树

346 阅读1分钟

在一些业务需求中,比如以树形图构建部门,那么如何处理后端返回来的数据呢?

image.png

这里后端一般返回的数据是数组,那么我们就需要用到数组转树,主要将数组转换为对象同时增加唯一id(key)。且添加children属性,用来增加子树。

// 数组转树数据处理
const arr=[{id:1,name:'zs'},{id:2,name:'ls'},{id:3,name:'ww'}]
const map={}
arr.forEach(item => {
    // 1.创建键值对,key为item.id,value为item对象
    map[item.id]=item

    // 2.给第一步创建的键值对的值(数据类型为对象),增加属性children
    map[item.id].children=[]
});

console.log(map)
/* 
{
  '1': { id: 1, name: 'zs', children: [] },
  '2': { id: 2, name: 'ls', children: [] },
  '3': { id: 3, name: 'ww', children: [] }
} 
*/



for(let key in map){
    console.log(key+map[key].toString)
}
/* 
1function toString() { [native code] }
2function toString() { [native code] }
3function toString() { [native code] }
*/



console.log(Object.keys(map))
// [ '1', '2', '3' ]



console.log(Object.values(map))
/* 
[
  { id: 1, name: 'zs', children: [] },
  { id: 2, name: 'ls', children: [] },
  { id: 3, name: 'ww', children: [] }
]
*/