function flattenTree(tree, callback) {
const stack = [...tree];
const result = [];
while (stack.length) {
const node = stack.shift();
result.push(node);
console.log(666.001, [...result.map(callback || ((item) => item))]);
if (node.children && node.children.length) {
stack.unshift(...node.children);
}
}
return result.map(callback || ((item) => item));
}
const treeData = [
{
id: 1,
title: "Node 1",
children: [
{
id: 2,
title: "Node 1.1",
children: [
{
id: 3,
title: "Node 1.1.1",
children: [
{
id: 4,
title: "Node 1.1.1.1",
children: [{ id: 5, title: "Node 1.1.1.1.1" }],
},
],
},
],
},
],
},
{ id: 6, title: "Node 2" },
{
id: 7,
title: "Node 3",
children: [
{
id: 8,
title: "Node 3.1",
children: [
{
id: 9,
title: "Node 3.1.1",
children: [
{
id: 10,
title: "Node 3.1.1.1",
children: [{ id: 11, title: "Node 3.1.1.1.1" }],
},
],
},
],
},
],
},
];
const flatList = flattenTree(treeData, (item) => item.id);
console.log(666.002, flatList);