or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-flat

Take a nested Javascript object and flatten it, or unflatten an object with delimited keys

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/flat@6.0.x

To install, run

npx @tessl/cli install tessl/npm-flat@6.0.0

index.mddocs/

Flat

Flat is a lightweight JavaScript utility library that provides functionality to flatten deeply nested objects into single-level objects with dot-notation keys, and the reverse operation of unflattening such objects back to their nested structure. It offers configurable options including custom delimiters, maximum depth limits, safe array handling, key transformation functions, and overwrite behavior for conflicting keys.

Package Information

  • Package Name: flat
  • Package Type: npm
  • Language: JavaScript (ES modules with TypeScript definitions)
  • Installation: npm install flat

Core Imports

import { flatten, unflatten } from "flat";

For TypeScript projects:

import { flatten, unflatten, FlattenOptions, UnflattenOptions } from "flat";

Basic Usage

import { flatten, unflatten } from "flat";

// Flatten a nested object
const nested = {
  key1: {
    keyA: 'valueI'
  },
  key2: {
    keyB: 'valueII'
  },
  key3: { a: { b: { c: 2 } } }
};

const flattened = flatten(nested);
// Result: {
//   'key1.keyA': 'valueI',
//   'key2.keyB': 'valueII',
//   'key3.a.b.c': 2
// }

// Unflatten back to nested structure
const restored = unflatten(flattened);
// Result: original nested object

Capabilities

Object Flattening

Takes a nested JavaScript object and flattens it into a single-level object with dot-notation keys.

/**
 * Flattens a nested object into a single-level object with dot-notation keys
 * @param target - The object to flatten
 * @param opts - Optional configuration object
 * @returns Flattened object with dot-notation keys
 */
function flatten<T, R>(target: T, opts?: FlattenOptions): R;

interface FlattenOptions {
  /** Custom delimiter for keys (default: '.') */
  delimiter?: string;
  /** Maximum depth to flatten (default: unlimited) */
  maxDepth?: number;
  /** Preserve arrays and their contents without flattening (default: false) */
  safe?: boolean;
  /** Transform function applied to each key during flattening */
  transformKey?: (key: string) => string;
}

Usage Examples:

import { flatten } from "flat";

// Basic flattening
const basic = flatten({
  user: {
    name: 'John',
    address: {
      street: '123 Main St',
      city: 'Boston'
    }
  }
});
// Result: {
//   'user.name': 'John',
//   'user.address.street': '123 Main St',
//   'user.address.city': 'Boston'
// }

// Custom delimiter
const customDelim = flatten(basic, { delimiter: '/' });
// Result: {
//   'user/name': 'John',
//   'user/address/street': '123 Main St',
//   'user/address/city': 'Boston'
// }

// Maximum depth
const limited = flatten({
  level1: {
    level2: {
      level3: {
        level4: 'deep'
      }
    }
  }
}, { maxDepth: 2 });
// Result: {
//   'level1.level2': { level3: { level4: 'deep' } }
// }

// Safe mode (preserve arrays)
const withArrays = flatten({
  items: [
    { name: 'item1' },
    { name: 'item2' }
  ]
}, { safe: true });
// Result: {
//   'items': [{ name: 'item1' }, { name: 'item2' }]
// }

// Key transformation
const transformed = flatten({
  firstName: 'John',
  lastName: 'Doe'
}, {
  transformKey: (key) => `__${key}__`
});
// Result: {
//   '__firstName__': 'John',
//   '__lastName__': 'Doe'
// }

Object Unflattening

Takes a flattened object with dot-notation keys and reconstructs the original nested structure.

/**
 * Unflattens a flat object with dot-notation keys back into nested structure
 * @param target - The flattened object to unflatten
 * @param opts - Optional configuration object
 * @returns Nested object structure
 */
function unflatten<T, R>(target: T, opts?: UnflattenOptions): R;

interface UnflattenOptions {
  /** Custom delimiter for keys (default: '.') */
  delimiter?: string;
  /** Prevent automatic array creation for numeric keys (default: false) */
  object?: boolean;
  /** Allow overwriting existing keys during unflattening (default: false) */
  overwrite?: boolean;
  /** Transform function applied to each key segment during unflattening */
  transformKey?: (key: string) => string;
}

Usage Examples:

import { unflatten } from "flat";

// Basic unflattening
const basic = unflatten({
  'user.name': 'John',
  'user.age': 30,
  'user.address.city': 'Boston'
});
// Result: {
//   user: {
//     name: 'John',
//     age: 30,
//     address: {
//       city: 'Boston'
//     }
//   }
// }

// Array creation (default behavior)
const withArrays = unflatten({
  'users.0.name': 'John',
  'users.1.name': 'Jane'
});
// Result: {
//   users: [
//     { name: 'John' },
//     { name: 'Jane' }
//   ]
// }

// Prevent array creation
const asObjects = unflatten({
  'users.0.name': 'John',
  'users.1.name': 'Jane'
}, { object: true });
// Result: {
//   users: {
//     '0': { name: 'John' },
//     '1': { name: 'Jane' }
//   }
// }

// Overwrite behavior
const withOverwrite = unflatten({
  'TRAVIS': 'true',
  'TRAVIS.DIR': '/home/travis/build'
}, { overwrite: true });
// Result: {
//   TRAVIS: {
//     DIR: '/home/travis/build'
//   }
// }

// Custom delimiter and key transformation
const custom = unflatten({
  '__user__/__name__': 'John',
  '__user__/__age__': 30
}, {
  delimiter: '/',
  transformKey: (key) => key.substring(2, key.length - 2)
});
// Result: {
//   user: {
//     name: 'John',
//     age: 30
//   }
// }

Command Line Interface

The package includes a command-line tool for flattening JSON files.

# Flatten a JSON file
flat input.json

# Flatten JSON from stdin
cat data.json | flat
echo '{"a":{"b":1}}' | flat

Usage Examples:

# Create a sample nested JSON file
echo '{"user":{"name":"John","details":{"age":30,"city":"Boston"}}}' > sample.json

# Flatten it using the CLI
flat sample.json
# Output: {
#   "user.name": "John",
#   "user.details.age": 30,
#   "user.details.city": "Boston"
# }

# Use with pipes
curl -s https://api.example.com/user | flat

Error Handling

The flat package handles several edge cases and provides protection against common issues:

  • Prototype Pollution Protection: Keys named __proto__ are automatically filtered out during unflattening
  • Buffer Detection: Automatically detects and preserves Buffer objects without flattening
  • Type Safety: Maintains original data types through the flatten/unflatten cycle
  • Circular Reference Handling: While not explicitly handled, the library will process objects as encountered

Performance Considerations

  • Zero Dependencies: No runtime dependencies for maximum compatibility and minimal overhead
  • Lazy Evaluation: Operations are performed immediately without complex queuing
  • Memory Efficient: Creates new objects without mutating originals
  • ES Module Support: Supports tree-shaking for optimal bundle sizes