面试一脸懵:listToTree

const tree = [
  {
    
    id: -1,parentId: null},
  {
    
    id: 0,parentId: -1},
  {
    
    id: 1,parentId: -1},
  {
    
    id: 2,parentId: -1},
  {
    
    id: 3, parentId: 2},
  {
    
    id: 4, parentId: 3},
]
转化为
[{
    
    "id":-1,"children":[{
    
    "id":0},{
    
    "id":1},{
    
    "id":2,"children":[{
    
    "id":3,"children":[{
    
    "id":4}]}]}]}]
function listToTree(list){
    
    
	let map = new Map()
	list.forEach(item=>{
    
    
		if(!map.has(item.parentId)){
    
    
			map.set(item.parentId, [])
		}
		map.get(item.parentId).push(item)
	})	
	function rev(root){
    
    
		return map.get(root).map(item=>{
    
    
			if(map.has(item.id)){
    
    
				item.children = rev(item.id)
			}
			delete item.parentId
			return item
		})
	}
	return rev(null)
}	

猜你喜欢

转载自blog.csdn.net/m0_37285193/article/details/121744285