每個元素全字段
const flatten = (data)=> data.reduce((arr, item)=> arr.concat([item], flatten(item.childrenList)), []);
const list = [
{id: 1, name: 1, pid: -1, childrenList: [
{id: 7, name: 7, pid: 1, childrenList: []},
{id: 8, name: 8, pid: 1, childrenList: []},
{id: 9, name: 9, pid: 1, childrenList: []},
]},
{id: 2, name: 2, pid: -1, childrenList: [
{id: 3, name: 3, pid: 2, childrenList: []},
{id: 4, name: 4, pid: 2, childrenList: []},
{id: 5, name: 5, pid: 2, childrenList: []},
{id: 6, name: 6, pid: 2, childrenList: []},
]},
];
flatten(list);
[
{"id":1,"name":1,"pid":-1,"childrenList":[
{"id":7,"name":7,"pid":1,"childrenList":[]},
{"id":8,"name":8,"pid":1,"childrenList":[]},
{"id":9,"name":9,"pid":1,"childrenList":[]}
]},
{"id":7,"name":7,"pid":1,"childrenList":[]},
{"id":8,"name":8,"pid":1,"childrenList":[]},
{"id":9,"name":9,"pid":1,"childrenList":[]},
{"id":2,"name":2,"pid":-1,"childrenList":[
{"id":3,"name":3,"pid":2,"childrenList":[]},
{"id":4,"name":4,"pid":2,"childrenList":[]},
{"id":5,"name":5,"pid":2,"childrenList":[]},
{"id":6,"name":6,"pid":2,"childrenList":[]}
]},
{"id":3,"name":3,"pid":2,"childrenList":[]},
{"id":4,"name":4,"pid":2,"childrenList":[]},
{"id":5,"name":5,"pid":2,"childrenList":[]},
{"id":6,"name":6,"pid":2,"childrenList":[]}
]
每個元素部分字段
const flatten = (data)=> data.reduce((arr, {id, name, pid, childrenList = []})=> arr.concat([{id, name, pid}], flatten(childrenList)), []);
const list = [
{id: 1, name: 1, pid: -1, childrenList: [
{id: 7, name: 7, pid: 1, childrenList: []},
{id: 8, name: 8, pid: 1, childrenList: []},
{id: 9, name: 9, pid: 1, childrenList: []},
]},
{id: 2, name: 2, pid: -1, childrenList: [
{id: 3, name: 3, pid: 2, childrenList: []},
{id: 4, name: 4, pid: 2, childrenList: []},
{id: 5, name: 5, pid: 2, childrenList: []},
{id: 6, name: 6, pid: 2, childrenList: []},
]},
];
flatten(list);
[
{"id":1,"name":1,"pid":-1},
{"id":7,"name":7,"pid":1},
{"id":8,"name":8,"pid":1},
{"id":9,"name":9,"pid":1},
{"id":2,"name":2,"pid":-1},
{"id":3,"name":3,"pid":2},
{"id":4,"name":4,"pid":2},
{"id":5,"name":5,"pid":2},
{"id":6,"name":6,"pid":2}
]