代码
flatteningData(arr, returnArr, isChildren=false, id='pid', pid='id', branch='children'){
let list = returnArr , data = {}
arr = JSON.parse(JSON.stringify(arr))
while(data = arr.shift()){
const {[branch]:children, ...item} = data
list.push(isChildren ? data : item)
if(children && children.length){
this.flatteningData(children, list, isChildren, id, pid, branch)
}
}
return list
}
案例
test(){
const arr = [
{
text:'吃食',
id:1,
children:[
{
text:'水果',
id:11,
children:[
{
text:'苹果',
id:111
},
{
text:'葡萄',
id:112
},
{
text:'梨子',
id:113
}
]
},
{
text:'零食',
id:12,
children:[
{
text:'锅巴',
id:121
},
{
text:'辣条',
id:122
}
]
},
{
test:'肉类',
id:13,
children:[
{
text:'鸭肉',
id:131
},
{
text:'鸡肉',
id:132
}
]
}
]
}
]
console.log('结果111', this.flatteningData(arr, []))
}
[
{
"text": "吃食",
"id": 1
},
{
"text": "水果",
"id": 11
},
{
"text": "苹果",
"id": 111
},
{
"text": "葡萄",
"id": 112
},
{
"text": "梨子",
"id": 113
},
{
"text": "零食",
"id": 12
},
{
"text": "锅巴",
"id": 121
},
{
"text": "辣条",
"id": 122
},
{
"test": "肉类",
"id": 13
},
{
"text": "鸭肉",
"id": 131
},
{
"text": "鸡肉",
"id": 132
}
]