牛客网笔试题

        let results = {
            data: [
                {
                    name: 'name1',
                    type: 't1',
                },
                {
                    name: 'name2',
                    type: 't2',
                    children: [
                        {
                            name: 'name3',
                            type: 't3',
                            children: [
                                {
                                    name: 'n7',
                                    type: 't2',
                                    children: [
                                        {
                                            name: 'n8',
                                            type: 't2',
                                        },
                                    ],
                                },
                            ],
                        },
                        {
                            name: 'name4',
                            type: 't1',
                            children: [
                                {
                                    name: 'n6',
                                    type: 't2',
                                },
                            ],
                        },
                    ],
                },
                {
                    name: 'name5',
                    type: 't3',
                },
            ],
        };

        //经过函数fun1的处理,过滤掉所有type=t1的节点及其子节点。
        // let newArr = [];
        function fun1(arr) {
            let newArr = [];
            arr.forEach((i) => {
                if (i.type !== 't1') {
                    if (!('children' in i)) {
                        newArr.push(i);
                    } else {
                        newArr.push({
                            name: i.name,
                            type: i.type,
                            children: fun1(i.children),
                        });
                    }
                }
            });
            return newArr;
        }
        console.log(fun1(results['data']));

你可能感兴趣的:(javascript)