Flatten object javascript recursively

Flatten object javascript recursively

how to flatten object in JavaScript.

Interviewer :

Can you flatten an object, Please take the below as input

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

and produce output like this.

{
    name : "test",
    address_personal: "abc"
    address_office_building: "random"
    address_office_street: "some street"
}

Here you go, this 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);

If you want to see more interview questions please reach out to 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

dev.to: https://dev.to/imranmind

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