JavaScript

Flatten Object (Dot Notation)

by @admin
12h ago
Apr 28, 2026
Public
Flattens a deeply nested object into a single-level object with dot-notation keys. Useful for comparing configs, building form field names from nested data, logging structured objects to analytics, or preparing data for flat key-value stores like Redis or environment variables.
JavaScript
function flattenObject(obj, prefix = '', result = {}) {
  for (const [key, val] of Object.entries(obj)) {
    const newKey = prefix ? `${prefix}.${key}` : key;
    if (val && typeof val === 'object' && !Array.isArray(val)) {
      flattenObject(val, newKey, result);
    } else {
      result[newKey] = val;
    }
  }
  return result;
}

// Usage
const config = { db: { host: 'localhost', port: 5432 }, app: { name: 'MyApp' } };
console.log(flattenObject(config));
// { 'db.host': 'localhost', 'db.port': 5432, 'app.name': 'MyApp' }
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.