JSPM

nested-object-to-key-value

1.0.8
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 16
  • Score
    100M100P100Q44317F
  • License MIT

A lightweight utility to flatten nested JavaScript objects into dot-notation key-value pairs and unflatten them back. Perfect for handling complex configurations, form data, or API transformations.

Package Exports

    Readme

    ๐Ÿฆค Nested objects to key value

    build and test workflow npm version License: MIT TypeScript

    A lightweight utility to flatten nested JavaScript objects into dot-notation key-value pairs and unflatten them back. Perfect for handling complex configurations, form data, or API transformations.

    Features

    • ๐ŸŽฏ Zero dependencies
    • ๐Ÿ“ฆ Lightweight (~XKB gzipped)
    • ๐Ÿ’ช Fully typed (TypeScript)
    • ๐Ÿ” Preserves type information
    • โšก Tree-shakeable
    • ๐Ÿงช Well tested

    ๐Ÿ“ฆ Installation

    npm install nested-object-to-key-value

    ๐Ÿ“š Usage

    import { flattenJson, unflattenJson } from "nested-object-to-key-value";
    // Flatten a nested object
    const nested = {
    user: {
            name: "John",
            address: {
                city: "New York",
                country: "USA",
            },
        },
    };
    const flattened = flattenJson(nested);
    // Result:
    // [
    //   { key: "user.name", value: "John" },
    //   { key: "user.address.city", value: "New York" },
    //   { key: "user.address.country", value: "USA" }
    // ]
    
    // Unflatten back to nested object
    const flat = {
        "user.name": "John",
        "user.address.city": "New York",
        "user.address.country": "USA",
    };
    const unflattened = unflattenJson(flat);
    // Result:
    // {
    //   user: {
    //   name: "John",
    //   address: {
    //   city: "New York",
    //   country: "USA"
    // }
    // }
    // }
    
    

    ๐Ÿ“˜ API

    flattenJson(obj: UnflattenedJson, prefix?: string): FlattenedPair[]

    Converts a nested object into an array of flattened key-value pairs.

    unflattenJson(obj: Record<string, string>): UnflattenedJson

    Converts a flat object with dot-notation keys back into a nested object.

    keyValueArrayToObject(obj: FlattenedPair[]): Record<string, string>

    Converts an array of key-value pairs into a flat object.

    ๐Ÿšฒ Testing

    We use Vitest for testing.

    npm test

    ๐Ÿค Contributing

    Contributions are welcome! Please open an issue or submit a pull request.

    ๐Ÿ“ License

    MIT