DEV Community

Suvadeep Majumdar
Suvadeep Majumdar

Posted on

Flattening an object

Problem Statement
Suppose we have an object with any depth(let say 5, "obj.a.b.c.d.e"), our target is to return an object with a depth of just 1, for example,

obj = {
    a: {
        b:1,
        c: {
            d: 10
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

should get converted to:

obj = {
    a.b: 1,
    a.c.d: 10
}
Enter fullscreen mode Exit fullscreen mode

My Approach
Think Recursively!
We would drill down the object and check at each level whether it is an object(and not Array).

  1. If yes drill further through that sub-object and keep track of all the keys covered till now. For that I am passing an array(retArr) as a spread operator.
  2. If not just assign the value against the key array(retArr) converted to string using join(".").

My code:

const obj = {
    a: {
        b:1,
        c: {
            d: 10,
            x: function () {
                console.log("AAA")
            }
        }
    }, e: {
        f: 5,
        g: {
            h: "hii",
            y: [1,2,3,4,5]
        }, 
        i: {
            j: {
                k:3,
                l: {
                    m: 20,
                },
                n: {
                    o:10
                },
                p: "hello"
            }
        }
    }
}
let retObj = {};
function flattenUtil (obj, ...keyArr) {
    for(x in obj) {
        if(typeof obj[x] === 'object' && !Array.isArray(obj[x])) {
            flattenUtil(obj[x], ...[...keyArr, x]);
        } else {
            retObj[[...keyArr, x].join(".")] = obj[x];
        }
    }
    return retObj;
}
console.log(flattenUtil(obj));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)