在工作当中会收到后端朋友返回的一些数据,在当中有一组数据的结构可能让新手前端朋友感到困扰。比如 数组里有父级内容和对应的子内容都在一个层次里面,而不是树形结构,拿他来直接循环两层或者三层内容有点麻烦,那应该怎么办呢?废话不多说,直奔主题。
// 需要处理的数组长这样,父级和子极都在一个数组里
let menu = [
{ id: 0, name: 'Home', link: '/home', parentId: null },
{ id: 1, name: 'Products', link: '/products', parentId: null },
{ id: 2, name: 'Electronics', link: '/products/electronics', parentId: 1 },
{ id: 3, name: 'Clothing', link: '/products/clothing', parentId: 1 },
{ id: 4, name: 'Books', link: '/products/books', parentId: 1 },
{ id: 5, name: 'Services', link: '/services', parentId: null },
{ id: 6, name: 'Consulting', link: '/services/consulting', parentId: 5 },
{ id: 7, name: 'Development', link: '/services/development', parentId: 5 },
{ id: 8, name: 'Design', link: '/services/design', parentId: 5 },
{ id: 9, name: 'About Us', link: '/about', parentId: null },
{ id: 10, name: 'Contact', link: '/contact', parentId: null }
];
这时候我们可以用到我们的一个老朋友 递归函数!
// 递归函数
const getTreeData = (oldList,id,newlist)=>{
for(let item of oldList){
if (item.parentId == id) {
newlist.push(item)
}
}
for (let v of newlist) {
v.children = [];
getTreeData(menu,v.id,v.children);
if (v.children == 0) {
delete v.children;
}
}
return newlist;
}
const resultTreeData = getTreeData(menu,null,[])
console.log(resultTreeData,'最终结果')
得到的结果: