Рекурсия есть:
const flat = (arr, childrenKey) =>
arr instanceof Array
? arr.flatMap(({ [childrenKey]: c, ...n }) => [ n, ...flat(c, childrenKey) ])
: [];
const result = flat(items, 'children');
Рекурсии нет:
function flat(arr, childrenKey) {
const result = [];
for (const stack = [...arr].reverse(); stack.length;) {
const { [childrenKey]: c, ...n } = stack.pop();
if (Array.isArray(c) && c.length) {
stack.push(...[...c].reverse());
}
result.push(n);
}
return result;
}
// или
function flat(arr, childrenKey) {
const result = [];
const stack = [];
for (let i = 0; i < arr.length || stack.length; i++) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else {
const { [childrenKey]: c, ...n } = arr[i];
if (c?.constructor === Array && c.length) {
stack.push([ i, arr ]);
[ i, arr ] = [ -1, c ];
}
result.push(n);
}
}
return result;
}
// или
function flat([...arr], childrenKey) {
for (const [ i, { [childrenKey]: c, ...n } ] of arr.entries()) {
arr.splice(i, 1, n, ...(c?.[Symbol.iterator] && typeof c !== 'string' ? c : []));
}
return arr;
}