#javascript# 數組扁平化

let arr = [{
    a:1,
    children: [
        {b: 2},
        {c: 3}
    ]
}, {
    d:4,
    children: [
        {e: 5},
        {f: 6}
    ]
}]

// 數組扁平化
function flatten(arr) {
    return [].concat(...arr.map(item => {
        if (item.children && item.children.length > 0) {
            return [].concat(item, ...flatten(item.children))
        } else if (item.children) {
            return [].concat(item, ...item.children)
        }
        return item
    }))
}

const newArr = flatten(arr)

console.log(newArr)

// 輸出結果
// [
//     { a: 1, children: [ [Object], [Object] ] },
//     { b: 2 },
//     { c: 3 },
//     { d: 4, children: [ [Object], [Object] ] },
//     { e: 5 },
//     { f: 6 }
//   ]
  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章