[
{
"id": 1,
"title": "1",
"children": [
{
"id": 2,
"title": "1.1",
},
{
"id": 3,
"title": "1.2",
},
{
"id": 4,
"title": "1.3",
"children": [],
},
{
"id": 5,
"title": "1.4",
"children": [
{
"id": 6,
"title": "1.4.1",
"children": [],
},
{
"id": 7,
"title": "1.4.2",
}
],
},
{
"id": 8,
"title": "1.5",
}
]
},
{
"id": 2,
"title": "2",
"children": [],
}
],

vue.js数组中有多个子级,怎么把他们全部拼接到单个数组同一级中
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
5条回答 默认 最新
- 小小码农,可笑可笑 2021-04-29 11:24关注
item.children.length > 0改为item.children && item.children.length > 0即可,仅判断item.children.length > 0可能会存在item.children不存在,导致item.children.length报错undifined。基本就是雨生百谷老铁的代码
export function FlatArray (data) { console.log('原数组长度:', data.length) if (data.length === 0) { return [] } let arr = [] data.map((item) => { if (item.children && item.children.length > 0) { arr = arr.concat(FlatArray(item.children)) } else { item.children = [] } arr.push(item) }) console.log('打平后数组长度:', arr.length) return arr }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 2无用