reduce 树结构数组转为扁平数组

每个元素全字段

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}
]

版权声明:本文为mazhili1991原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。