多维数组变成一维数组 很多文章写的答案都不对,给纠正下

179 阅读1分钟
const oldArr = [
    {
        id: 1,
        title: 'name1'
    },
    {
        id: 2,
        title: 'name2',
        children: [
                {
                    id: 3,
                    title: 'name3'
                },
                {
                    id: 4,
                    title: 'name4',
                    children: [
                        {
                            id: 5,
                            title: 'name5'
                        }
                    ]
                }
        ]
    },
    {
        id: 6,
        title: 'name6'
    },
    {
        id: 7,
        title: 'name7'
    }
]
let flatten = (arr) => {
        let res = [];
        for (let i = 0; i < arr.length; i++) {
                res.push(arr[i])
                if (Array.isArray(arr[i].children)) {
                        res = res.concat(flatten(arr[i].children))
                }
                delete arr[i].children
        }
        return res;
}
console.log(flatten(oldArr));