数据结构为 (children为null、空[] 或 没有):
let arr = [{
id: 1,
name: 'A1',
children: [{
id: 2,
name: 'A2',
children: [{
id: 3,
name: 'A3',
children: null
}]
},{
id: 4,
name: 'A4',
children: [{
id: 5,
name: 'A5',
children: []
}]
}]
},{
id: 6,
name: 'A6',
children: [{
id: 7,
name: 'A7'
}]
}]
处理方式:
// 格式数据
function setFormData(obj) {
return JSON.parse(JSON.stringify(obj))
}
// 多维数组转为一维数组
function moreToOne(arr) {
let res = []
if (!(arr instanceof Array)) return res
arr.forEach(item => {
// 储存当前项
let newItem = setFormData(item)
delete newItem.children
res.push(newItem)
// 是否有子项
if (Array.isArray(item.children) && item.children.length > 0) {
// 处理子项
res = res.concat(moreToOne(item.children))
}
})
return res
}
// 返回结果
[
{
"id": 1,
"name": "A1"
},
{
"id": 2,
"name": "A2"
},
{
"id": 3,
"name": "A3"
},
{
"id": 4,
"name": "A4"
},
{
"id": 5,
"name": "A5"
},
{
"id": 6,
"name": "A6"
},
{
"id": 7,
"name": "A7"
}
]