How to Flatten an Object in Javascript ?
Imran shaikh
Posted on May 2, 2023
Interviewer :
Can you flatten an object, Please take below as input
const obj = {
name: "test",
address: {
personal: "abc",
office: {
building: 'random',
street: 'some street'
}
}
}
and produce output like below
{
name : "test",
address_personal: "abc"
address_office_building: "random"
address_office_street: "some street"
}
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);
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.
💖 💪 🙅 🚩
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.