Skip to main content
InterviewHubPRO
Section Overview
Q527

Question 527 of 536

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)

98%
JavaScript & V8 Internals (536 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)

How do you deeply flatten and unflatten a nested JavaScript object with dot notation?

mid LevelCode ExampleFormsPerformanceHTTP & REST APIs

A classic frontend machine-coding interview question testing recursion, object traversal, and nested reference construction.

1. Flattening an Object (flattenObject)

Given a deeply nested object, transform it into a single-level object whose keys represent property paths separated by dots (.):

javascript
function flattenObject(obj, prefix = '', result = {}) {
  for (const [key, value] of Object.entries(obj)) {
    const newKey = prefix ? `${prefix}.${key}` : key;

    if (
      value !== null &&
      typeof value === 'object' &&
      !Array.isArray(value) &&
      Object.keys(value).length > 0
    ) {
      flattenObject(value, newKey, result);
    } else {
      result[newKey] = value;
    }
  }
  return result;
}

const user = {
  name: "Sarah",
  address: {
    city: "San Francisco",
    coordinates: {
      lat: 37.7749,
      lng: -122.4194
    }
  },
  roles: ["admin", "editor"]
};

console.log(flattenObject(user));
/* Output:
{
  "name": "Sarah",
  "address.city": "San Francisco",
  "address.coordinates.lat": 37.7749,
  "address.coordinates.lng": -122.4194,
  "roles": ["admin", "editor"]
}
*/

2. Unflattening an Object (unflattenObject)

The inverse operation: reconstructing the nested tree structure from dot-notation keys:

javascript
function unflattenObject(flatObj) {
  const result = {};

  for (const [keyPath, value] of Object.entries(flatObj)) {
    const keys = keyPath.split('.');
    let current = result;

    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];

      if (i === keys.length - 1) {
        current[key] = value;
      } else {
        if (!current[key] || typeof current[key] !== 'object') {
          current[key] = {};
        }
        current = current[key];
      }
    }
  }

  return result;
}

const flat = {
  "name": "Sarah",
  "address.city": "San Francisco",
  "address.coordinates.lat": 37.7749
};

console.log(unflattenObject(flat));
// { name: "Sarah", address: { city: "San Francisco", coordinates: { lat: 37.7749 } } }