How to Flatten an Object in Javascript ?

imranmind

Imran shaikh

Posted on May 2, 2023

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.

💖 💪 🙅 🚩
imranmind
Imran shaikh

Posted on May 2, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related