之前朋友问过我一个问题,项目中遇到树状结构的数组不知如何扁平化,下面贴一下问题和解决方案:
以下是需要做处理的数据:
var arr = [
{
id: 1,
name: 'a',
child: [
{
id: 2,
name: 'b',
child: [
{
id: 3,
name: 'c',
child: [],
},
],
},
],
},
{
id: 4,
name: 'd',
child: [
{
id: 5,
name: 'e',
child: [
{
id: 6,
name: 'f',
child: [],
},
],
},
],
},
]
需求是需要把每一级的child中的内容拉到第一级中,并去掉child属性,拿到问题无非就是只要有child层级,就拿它的属性过来,填充到新数组中,无限递归下去。
下面是解决方案:
// 方法一
function flag(arr) {
let result = []
for (item of arr) {
var res = JSON.parse(JSON.stringify(item)) // 先克隆一份数据作为第一层级的填充
delete res['child']
result.push(res)
if (item.child instanceof Array && item.child.length > 0) { // 如果当前child为数组并且长度大于0,才可进入flag()方法
result = result.concat(flag(item.child))
}
}
return result
}
console.log(flag(arr))
// 方法二
var array = []
function getData(arr, type = 'child') {
arr.forEach((res) => {
var resType = JSON.parse(JSON.stringify(res)) // 先克隆一份数据作为第一层级的填充
delete resType[type]
array.push(resType)
if (Array.isArray(res[type]) && res[type].length > 0) { // 如果当前child为数组并且长度大于0,才可进入flag()方法
getData(res[type])
}
})
return array
}
console.log(getData(arr))
其实两种方法逻辑相同,只是细节上的写法有出入,看个人习惯,并且新数组的作用域不同,所以方法一才需要concat()。
两种方法输出结果一致。
输出结果:
[ { id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
{ id: 4, name: 'd' },
{ id: 5, name: 'e' },
{ id: 6, name: 'f' } ]