fudx / learnNotes

刷题笔记哦
0 stars 0 forks source link

3、对象拍平demo #3

Open fudx opened 1 year ago

fudx commented 1 year ago
const data = {
    a:{
        b:1,
        c:{
            d:2,
            e:2,
            f:3
        }
    }
}

function flatten(data){
    // todo
}
flatten(data) // { 'a.b': 1, 'a.c.d': 2, 'a.c.e': 2, 'a.c.f': 3 }
fudx commented 1 year ago
function flatten(data) {
    // todo
    const ans = {}
    const dfs = (data,preFix)=>{
        if(typeof data === 'object') {
            for(let i in data) {
                preFix.push(i)
                if(typeof data[i] === 'object'){
                    dfs(data[i],preFix)
                } else {
                    ans[preFix.join('.')] = data[i]
                }
                preFix.pop()
            }
        }

    }
    dfs(data,[])
    console.log(ans)
    return ans
  }