我有一个像下面这样的树结构(没有深度限制,通常不超过6个子级别)。每个节点都有一个workItems属性,该属性是workItem对象的数组。

我想在每个节点上聚集workItems,以便一个节点包含其自己的workItems及其所有后代的workItems。

以下结构的示例,节点ID 11将具有workItems:

    [{ id: 'wi2' },
     { id: 'wi3' },
     { id: 'wi4' },
     { id: 'wi5' }] // aggregated from node `111`


节点1绝对具有树的所有workItems。

javascript

const traverse = (tree) => {
    const stack = [ tree ]

    while (stack.length) {
        const curr = stack.pop()

        // do something here, I guess

        stack.push(...curr.children)
    }
}


树状结构

    {
        id: '1',
        title: '1',
        workItems: [
            { id: 'wi1' }
        ],
        children: [
            {
                id: '11',
                title: '11',
                workItems: [
                    { id: 'wi2' },
                    { id: 'wi3' },
                    { id: 'wi4' }
                ],
                children: [
                    {
                        id: '111',
                        title: '111',
                        workItems: [
                            { id: 'wi5' },
                        ],
                        children: []
                    }
                ]
            },
            {
                id: '12',
                title: '12',
                workItems: [
                    { id: 'wi6' }
                ],
                children: [
                    {
                        id: '121',
                        title: '121',
                        workItems: [
                            { id: 'wi7' },
                            { id: 'wi8' }
                        ],
                        children: []
                    }
                ]
            }
        ]
    }


最佳答案

您可以进行深度优先搜索,然后移交workItmes的父数组以继续嵌套项目。



const
    getWorkItems = ({ workItems, children = [] }) =>
        (workItems.push(...children.flatMap(getWorkItems)), workItems);

var tree = { id: '1', title: '1', workItems: [{ id: 'wi1' }], children: [{ id: '11', title: '11', workItems: [{ id: 'wi2' }, { id: 'wi3' }, { id: 'wi4' }], children: [{ id: '111', title: '111', workItems: [{ id: 'wi5' }], children: [] }] }, { id: '12', title: '12', workItems: [{ id: 'wi6' }], children: [{ id: '121', title: '121', workItems: [{ id: 'wi7' }, { id: 'wi8' }], children: [] }] }] };

getWorkItems(tree);

console.log(tree);

.as-console-wrapper { max-height: 100% !important; top: 0; }

10-06 03:02