npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

flattener-kit

v1.0.1

Published

An object flatten/unflatten utility with OOP approach and transform support.

Readme

Flattener Kit

Flattener Kit is a lightweight and flexible utility to convert deeply nested objects or arrays into flattened structures—and vice versa. It supports a variety of custom configurations and follows an object-oriented design pattern, making it both reusable and extensible.


🚀 Features

  • Flatten nested Object and Array structures into a single-level object with dot/bracket notation.
  • Unflatten a flat object back to its original nested form.
  • Replace whole sub-paths instead of flattening (safes config).
  • Overwrite or merge behavior support during unflattening (overwrite config).
  • Highly configurable with reusable OOP design.

📦 Installation

npm install flattener-kit
# or
yarn add flattener-kit
# or
pnpm add flattener-kit

📘 Usage

Import the Class

import { Flattener } from 'flattener-kit';

1. Flatten a Simple Object

const payload = {
  name: 'John',
  address: {
    city: 'Anytown',
    zip: '12345',
  },
};

const flattener = new Flattener();
const flat = flattener.flatten(payload);

console.log(flat);

Output:

{
  "name": "John",
  "address.city": "Anytown",
  "address.zip": "12345"
}

2. Flatten with Array Support

const data = {
  user: {
    name: 'Alice',
    roles: ['admin', 'editor'],
  },
};

const flattener = new Flattener();
const result = flattener.flatten(data);

console.log(result);

Output:

{
  "user.name": "Alice",
  "user.roles.0": "admin",
  "user.roles.1.": "editor"
}

3. Use safe Config to Keep All Array as-is

const data = {
  user: {
    name: 'Bob',
    tags: ['dev', 'ops'],
    hobbies: ['reading', 'sports'],
  },
};

const flattener = new Flattener({ safe: true });
const result = flattener.flatten(data);

console.log(result);

Output:

{
  "user.name": "Bob",
  "user.tags": ["dev", "ops"],
  "user.hobbies": ['reading', 'sports']
}

4. Use safes Config to Keep Specific Array/Objects as-is

const data = {
  user: {
    name: 'Bob',
    tags: ['dev', 'ops'],
    hobbies: ['reading', 'sports'],
  },
};

const flattener = new Flattener({ safes: ['user.tags'] });
const result = flattener.flatten(data);

console.log(result);

Output:

{
  "user.name": "Bob",
  "user.tags": ["dev", "ops"],
  'user.hobbies.0': 'reading',
  'user.hobbies.1': 'sports',
}

5. Use a Custom delimiter

By default, the delimiter is ".". You can change it to anything, like "-" or "/".

const data = {
  product: {
    id: 101,
    details: {
      name: 'Book',
      price: 15,
    },
  },
};

const flattener = new Flattener({
  delimiter: '/',
});

const result = flattener.flatten(data);

console.log(result);

Output:

{
  "product/id": 101,
  "product/details/name": "Book",
  "product/details/price": 15
}

6. Use transformKey to Customize Key Formatting

You can pass a transformKey function to manipulate the flattened keys (e.g., to uppercase, kebab-case, etc.).

const data = {
  user: {
    name: 'Daisy',
    profile: {
      age: 30,
    },
  },
};

const flattener = new Flattener({
  transformKey: (key) => key.toUpperCase(),
});

const result = flattener.flatten(data);

console.log(result);

Output:

{
  "USER.NAME": "Daisy",
  "USER.PROFILE.AGE": 30
}

7. Unflatten a Flat Object

const flat = {
  'user.name': 'Charlie',
  'user.age': 28,
  'user.hobbies.0': 'reading',
  'user.hobbies.1': 'sports',
};

const flattener = new Flattener();
const nested = flattener.unflatten(flat);

console.log(nested);

Output:

{
  user: {
    name: "Charlie",
    age: 28,
    hobbies: ["reading", "sports"]
  }
}

8. Unflatten with Overwrite Object Config

const flat = {
  user: { isAdmin: true },
  'user.name': 'David',
};

const flattener = new Flattener({ overwrite: true });
const nested = flattener.unflatten(flat);

console.log(nested);

Output:

{
  user: {
    name: 'David';
  }
}

⚙️ Configuration

flatten(config?: FlattenConfig)

| Option | Type | Default | Description | | -------------- | ----------------------------------------- | ----------- | ------------------------------------------------------------------------------ | | delimiter | string | "." | Character used to join nested keys. | | safe | boolean | false | Prevents flattening arrays entirely. | | safes | string[] | [] | Array of specific paths to leave unflattened (dot/bracket notation supported). | | depth | number | Infinity | Maximum recursion depth for flattening. | | transformKey | (key: string, path: string[]) => string | undefined | Transforms each key during flattening. Useful for casing or formatting. |


unflatten(config?: UnflattenConfig)

| Option | Type | Default | Description | | -------------- | ----------------------------------------- | ----------- | -------------------------------------------------------------------------- | | delimiter | string | "." | Character used to split keys. | | overwrite | boolean | false | If true, existing non-object values will be overwritten during building. | | transformKey | (key: string, path: string[]) => string | undefined | Transforms each key before assignment. Useful for renaming or formatting. |


📘 Type Definitions

type Payload = Record<string, any> | any[];

type FlattenConfig = {
  delimiter?: string;
  safe?: boolean;
  safes?: string[];
  depth?: number;
};

type UnflattenConfig = {
  delimiter?: string;
  overwrite?: boolean;
  object?: boolean;
};

📁 Exports

export default Flattener;

📂 Use Cases

  • Sending deeply nested data through form submissions or APIs that require flat structures.
  • Normalizing data before storing in NoSQL databases or localStorage.
  • Creating key-value string maps for localization files (e.g., i18n).
  • Flattening complex payloads for logging or debugging purposes.
  • Data diffing, patching, or transformation logic.

✅ Test Coverage

  • Passed all unit tests for flatten and unflatten behavior
  • Supports deeply nested structures and edge cases

🧪 Testing

pnpm test

🌐 Repository

https://github.com/beendoo/flattener-kit.git


📝 License

MIT © Foysal Ahmed