Imran Shaikh
Imran Shaikh's Blog

Follow

Imran Shaikh's Blog

Follow
Flatten object javascript recursively

Flatten object javascript recursively

how to flatten object in JavaScript.

Imran Shaikh's photo
Imran Shaikh
·May 2, 2023·

1 min read

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.

 
Share this