senfish / blog

个人技术博客
4 stars 0 forks source link

17. 实现一个对象的`flatten`函数,满足如下需求 #17

Open senfish opened 3 years ago

senfish commented 3 years ago

let obj = {
    a: 1,
    b: [1, 2, {c: {d: true} }, [3], {e: [6, 7, 8] }],
    f: {g: 2, h: 3},
    i: null
}

function flatten(obj) {
  ...
}
flatten(obj)
// 输出
// {
//     'a': 1,
//     'b[0]': 1,
//     'b[1]': 2,
//     'b[2].c.d': true,
//     'b[3][0]': 3,
//     'b[4].e[0]': 6,
//     'b[4].e[1]': 7,
//     'b[4].e[2]': 8,
//     'f.g': 2,
//     'f.h': 3,
//     'i': null
// }
senfish commented 3 years ago

刚开始,首先想到了for ... in

function flatten(obj) {
    let map = {};
    const df = (obj, path = "", parentType = 'object') => {
        for(let key in obj) {
            if(Object.hasOwnProperty.call(obj, key)) {
                let rePath = ''
                if (parentType === 'object') {
                    rePath = `${path}.${key}`
                } else if (parentType === 'array') {
                    rePath = `${path}[${key}]`
                } else {
                    rePath = key;
                }
                if(Array.isArray(obj[key])) {
                    df(obj[key], rePath, 'array')
                } else if (typeof obj[key] === 'object' && obj[key] !== null) {
                    df(obj[key], rePath, 'object')
                } else {
                    map[rePath] = obj[key]
                }
            }
        }
    }
    df(obj, '', '');
    console.log(map);
}