nested-object-to-key-value
Version:
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.
94 lines (71 loc) โข 2.44 kB
Markdown
and test workflow](https://github.com/eivindingebrigtsen/nested-object-to-key-value/actions/workflows/ci.yml/badge.svg)](https://github.com/eivindingebrigtsen/nested-object-to-key-value/actions/workflows/ci.yml)
[](https://www.npmjs.com/package/nested-object-to-key-value)
[](https://opensource.org/licenses/MIT)
[](https://www.typescriptlang.org/)
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.
- ๐ฏ Zero dependencies
- ๐ฆ Lightweight (~XKB gzipped)
- ๐ช Fully typed (TypeScript)
- ๐ Preserves type information
- โก Tree-shakeable
- ๐งช Well tested
## ๐ฆ Installation
```bash
npm install nested-object-to-key-value
```
## ๐ Usage
```ts
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"
// }
// }
// }
```
Converts a nested object into an array of flattened key-value pairs.
Converts a flat object with dot-notation keys back into a nested object.
Converts an array of key-value pairs into a flat object.
We use [Vitest](https://vitest.dev/) for testing.
```bash
npm test
```
Contributions are welcome! Please open an issue or submit a pull request.
MIT
[![build