树形 多层嵌套 取出每层的id 放在一个数组中
let data = [ { firstLetter: 'A', fullName: '安徽省安庆市大观区', id: 1, childrens: [ { firstLetter: 'B', fullName: '安徽', id: 2, childrens: [ { firstLetter: 'D', fullName: '安徽', id: 3 }, { firstLetter: 'E', fullName: '安徽', id: 4, }, ], }, { firstLetter: 'C', fullName: '安徽', id: 5, childrens: [ { firstLetter: 'F', fullName: '安徽', id: 6 }, { firstLetter: 'G', fullName: '安徽', id: 7 },
{ firstLetter: 'H', fullName: '安徽', id: 8 } ], }, ], }, ]; let arr = []; function getIdFn(data){ data.forEach(item=>{ arr.push(item.id) if(item.hasOwnProperty("childrens")){ getIdFn(item.childrens) } }) return arr } let res = getIdFn(data) console.log('%c 🥩 res: ', 'font-size:20px;background-color: #7F2B82;color:#fff;', res)
//[1,2,3,4,5,6,7,8]


浙公网安备 33010602011771号