SOURCE

function extractNames(arr, result = [], path = {}) {
    for (const item of arr) {
        const newPath = { ...path };
        newPath['name' + Object.keys(newPath).length] = item.name;
        if (!item.children || item.children.length === 0) {
            result.push(newPath);
        } else {
            extractNames(item.children, result, newPath);
        }
    }
    return result;
}

// 示例数据
const nestedArray = [
    {
        name: 'A',
        children: [
            {
                name: 'B',
                children: [
                    { name: 'C1' },
                    { name: 'C2' }
                ]
            },
            {
                name: 'D',
                 children: [
                    { name: 'C1' },
                    { name: 'C2' }
                ]
            }
        ]
    }
];

// 测试函数
const namesArray = extractNames(nestedArray);
console.log(namesArray);
console 命令行工具 X clear

                    
>
console