DEV Community

Suvadeep Majumdar
Suvadeep Majumdar

Posted on

3 2

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay