flatten-to-key-value
Version:
Flatten JSON-like values into dot-path key/value pairs or unFlatten them back into nested objects, with support for arrays, dates, and customizable options.
130 lines (103 loc) • 2.79 kB
Markdown
or unflatten any JSON-like value.
- **Flatten**: turn objects into `{ "a.b.c": "value", ... }`.
- **Unflatten**: rebuild nested structures from flattened key/value pairs.
- Arrays of primitives aggregate into a single key and are joined (default `,`).
- Arrays of objects merge matching leaf paths across elements.
- Dates are serialized to ISO strings and restored back as `Date` objects when possible.
- Optional deduping, key sorting, delimiter and joiner customization.
## Install
```bash
npm i flatten-to-key-value
# or
pnpm add flatten-to-key-value
# or
yarn add flatten-to-key-value
```
## Usage
### ESM
```ts
import { flattenToKeyValue, unflattenKeyValue } from "flatten-to-key-value";
const input = {
user: { id: 1, name: "Ann" },
tags: ["a", "b", "b"],
purchases: [
{ sku: "X", qty: 1 },
{ sku: "Y", qty: 2 },
{ sku: "X", qty: 3 },
],
};
const flat = flattenToKeyValue(input, {
dedupeArrayValues: true,
sortKeys: true,
});
console.log(flat);
/*
{
"purchases.qty": "1,2,3",
"purchases.sku": "X,Y",
"tags": "a,b",
"user.id": "1",
"user.name": "Ann"
}
*/
const unflat = unflattenKeyValue(flat);
console.log(unflat);
/*
{
user: { id: 1, name: "Ann" },
tags: ["a", "b"],
purchases: [
{ qty: 1, sku: "X" },
{ qty: 2, sku: "Y" },
{ qty: 3, sku: "X" }
]
}
*/
```
```js
const {
flattenToKeyValue,
unflattenKeyValue,
} = require("flatten-to-key-value");
const out = flattenToKeyValue({ a: { b: [1, 2] } });
const back = unflattenKeyValue(out);
```
```ts
type FlattenOptions = {
delimiter?: string; // default "."
joiner?: string; // default ","
includeNullUndefined?: boolean; // default false (skips null/undefined)
dedupeArrayValues?: boolean; // default false
sortKeys?: boolean; // default false
};
function flattenToKeyValue(
input: unknown,
opts?: FlattenOptions
): Record<string, string>;
function unflattenKeyValue(
input: Record<string, string>,
opts?: FlattenOptions
): unknown;
```
- **Flatten**
- Top-level primitives result in an empty object (no anonymous key).
- Circular references fall back to `String(v)` for non-serializable values.
- Arrays of primitives: each element is collected under the same key and joined at the end.
- Arrays of objects: leaf paths are merged across elements—use `dedupeArrayValues: true` to remove repeats.
- **Unflatten**
- Keys are split by `delimiter` to rebuild objects.
- Joined values are split by `joiner` back into arrays.
- String values are parsed into numbers, booleans, `null`, `undefined`, `Date` objects, or JSON where possible.
- Single-element arrays are collapsed back to scalars.
## Development
```bash
pnpm i
pnpm test
pnpm build
```
## License
MIT
Flatten