js将扁平化数组整理成tree数组

162 阅读1分钟
 let arr = [
      { id: 1, name: '1', parentId: 0 },
      { id: 2, name: '2', parentId: 0 },
      { id: 3, name: '3', parentId: 0 },
      { id: 4, name: '1-1', parentId: 1 }
    ]

 // 方法一
  function arrToTree(arr, parentId = 0) {
      let newArr = []
      arr.forEach(item => {
        if (item.parentId === parentId) {
          newArr.push({
            ...item,
            children: arrToTree(arr, item.id)
          })
        }
      })
      return newArr
    }
    console.log(arrToTree(arr))

 //方法2
function arrToTree(arr,parentId = 0){
	return arr.filter(item => item.parentId === parentId).map(item => ({...item,children:arrToTree(arr,item.id)}))
}
console.log(arrToTree(arr));

 //方法3
function arrayToTree(items) {
    const result = []; // 存放结果集
    const itemMap = {}; // 
    for (const item of items) {
	const id = item.id;
	const pid = item.parentId;

	if (!itemMap[id]) {
            itemMap[id] = {
		children: [],
	   }
	}

	itemMap[id] = {
            ...item,
            children: itemMap[id]['children']
	}

        const treeItem = itemMap[id];

	if (pid === 0) {
            result.push(treeItem);
	} else {
            if (!itemMap[pid]) {
		itemMap[pid] = {
                    children: [],
		}
            }
                itemMap[pid].children.push(treeItem)
           }

	}
	return result;
} 
console.log(arrayToTree(arr));