DEV Community

Cover image for How to Flatten an Object in Javascript ?
Imran shaikh
Imran shaikh

Posted on

How to Flatten an Object in Javascript ?

Interviewer :
Image description Can you flatten an object, Please take below as input

const obj = {
    name: "test",
    address: {
        personal: "abc",
        office: {
            building: 'random',
            street: 'some street'
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

and produce output like below

{
    name : "test",
    address_personal: "abc"
    address_office_building: "random"
    address_office_street: "some street"
}
Enter fullscreen mode Exit fullscreen mode

Here is the solution.

const flattenObject = (obj, parentKey = '') => {
    if (parentKey !== '')
        parentKey = parentKey + '_';

    let flattened = {};
    console.log(flattened)
    Object.keys(obj).forEach((key) => {
        if (typeof obj[key] === 'object' && obj[key] !== null) {
            Object.assign(flattened, flattenObject(obj[key], parentKey + key))
        } else {
            flattened[parentKey + key] = obj[key]
        }
    })
    return flattened;
}


const obj = {
    name: "test",
    address: {
        personal: "abc",
        office: {
            building: 'random',
            street: 'some street'
        }
    }
}

let flat = flattenObject(obj);
console.log(flat);
Enter fullscreen mode Exit fullscreen mode

If you want to see more interview questions please reach out my GitHub profile

Github: https://github.com/imran-mind/javascript-notes/blob/master/JS-Interview-coding-ques/objectFlatten.js

Linkedin: https://www.linkedin.com/in/imran-mind

Twitter: https://twitter.com/imran1mind

My Blogs: https://imranshaikh.co.in/

If you find this blog helpful, please like and comment and don't forget to share this.

Top comments (0)