Flatten a Nested Object in JavaScript
2 min readJan 23, 2022
Flattening a JavaScript Nested Object is a very common question I came across in technical interviews.
Take the following input
object as an example.
const input = {
name: 'Mansi',
age: 25,
department: {
name: 'Customer Experience',
section: 'Technical',
branch: {
name: 'Bangalore',
timezone: 'IST'
}
},
company: {
name: 'SAP',
customers: ['Ford', 'Nestle']
},
skills: ['javascript', 'node.js', 'html']
}
The expected output
can be as follows:
const output = {
name: 'Mansi',
age: 25,
department_name: 'Customer Experience',
department_section: 'Technical',
department_branch_name: 'Bangalore',
department_branch_timezone: 'IST’,
company_name: 'SAP',
company_customers: ['Ford', 'Nestle'],
skills: ['javascript', 'node.js', 'html']
}
We’ll start by discussing naive solutions and then transition to the final solution that would be better in the aspects of Space & Time Complexity.
We’ll use two for .. in
to write a solution as follows:
const flattenObject = (input) => {
let result = {};
for (const key in input) {
if (!input.hasOwnProperty(key)) {
continue;
}
if (typeof input[key] === "object" &&!Array.isArray(input[key])) {
var subFlatObject…