All Interview Questions
About Lesson

Q2. You are given an object. Write a function to flatten it, where the term flatten is defined as to get all the keys of nested objects and bring them to the same level.

// # Sample Input:

const obj = {
    newObj: {
        obj2: {
            obj5: {
                one: 1,
                two: 2
            },
        },
    },
    obj3: {
        obj4: {
            two: 2
        },
    },
};
// # Sample Output:
/* {
    ‘newObj.obj2.obj5.one’: 1,
    ‘newObj.obj2.obj5.two’: 2,
    ‘obj3.obj4.two’: 2
}*/
Ans:
const flatten = (obj, parentKey=””, result = {})=>{
    for(const key in obj){
        const newKey = parentKey ? `${parentKey}.${key}` : key;
        const currObj = obj[key];
       
        if(typeof currObj === ‘object’ && currObj !== null && !Array.isArray(currObj)){
            flatten(currObj, newKey, result);
        }else{
            result[newKey] = obj[key];
        }
    }
    return result;
}

console.log(flatten(obj));

© GeekySanjay