今天出了一道数组扁平化的题目,小编写了两种方案,欢迎大家们踊跃参与评论可以写出更多更好的方法以供大家参考学习和交流。
- 积极参与哦小伙伴们~
题目:下面的数据多层树状结构处理成只有一层children的结构
data = [
{
name: "About",
path: "/about",
children: [
{
name: "About US",
path: "/about/us"
},
{
name: "About Comp",
path: "/about/company",
children: [
{
name: "About Comp A",
path: "/about/company/A",
children: [
{
name: "About Comp A 1",
path: "/about/company/A/1"
}
]
}
]
}
]
}
]
// 处理后的结构
[
{
name: "About",
path: "/about",
children: [
{
name: "About US",
path: "/about/us"
},
{
name: "About Comp",
path: "/about/company",
},
{
name: "About Comp A",
path: "/about/company/A"
},
{
name: "About Comp A 1",
path: "/about/company/A/1"
}
]
}
]
代码实现:
方法一
//递归遍历实现
var recursiveFunction4 = function(){
var aa=[]
const getStr = function(data){
data.forEach(item => {
aa.push({
name: item.name,
path: item.path
})
if(item.children?.length){
let children=getStr(item.children)
}
})
}
getStr(data[0].children)
//...展开运算符 因为前两项数据没变直接拿来用了拷贝 然后把最后一项children替换掉
aa= [{...data[0],children:aa}]
console.log(aa)
}
recursiveFunction4()//基于recursiveFunction3()优化
方法二
//写了一个可自由定义扁平化层级的代码,level代码不扁平的层级
function flatTree(data, level = 0, index = 0){
let result = [], obj;
data.forEach(item => {
result.push(obj = {
name: item.name,
path: item.path
})
if(item.children?.length){
let children = flatTree(item.children, level, index + 1)
if(level > index){
obj.children = children
}else{
result = result.concat(children)
}
}
})
return result
}
12.21更新~
题目:把树结构转为列表平行结构
//题目
let data = [
{
id: 1,
name: "hei",
children: [
{ id: 3, name: "bai" },
{ id: 4, name: "hong", children: [{ id: 6, name: "lv" }] }
]
},
{ id: 2, name: "jack", children: [{ id: 5, name: "lan" }] }
];
//转换成这个格式
let list = [
{ id: 1, name: "hei" },
{ id: 3, name: "bai" },
{ id: 4, name: "hong" },
{ id: 6, name: "lv" },
{ id: 2, name: "jack" },
{ id: 5, name: "lan" },
];
解题思路代码:
var data = [
{
id: 1,
name: "hei",
children: [
{ id: 3, name: "bai" },
{ id: 4, name: "hong", children: [{ id: 6, name: "lv" }] }
]
},
{ id: 2, name: "jack", children: [{ id: 5, name: "lan" }] }
];
var result = [];
function flatTree(data){
data.forEach(item => {
result.push({
id: item.id,
name: item.name
})
if(item.children?.length){
result=flatTree(item.children);
}
});
console.log(result)
return result
}
flatTree(data)