object-flatten-unflatten
v1.0.4
Published
A simple utility for flattening and unflattening JavaScript objects. This package provides functions to convert deeply nested objects into flat objects with keys and vice versa.
Readme
flatten-unflatten
A simple utility for flattening and unflattening JavaScript objects. This package provides functions to convert deeply nested objects into flat objects with keys and vice versa.
Installation
To install the package, use npm or yarn:
install:
npm install flatten-unflatten\flatten(object, options)
Flattens a nested object into a single-level object.
Arguments
object: The object to flatten (can be nested). options (optional): Configuration options (see below). Returns: A flattened object with dot-separated keys.
Available Options: delimiter (default: '.'): The delimiter to use between nested keys. For example, use '_' to flatten keys like user_name instead of user.name.
safe (default: false): If true, arrays will be flattened without modifying their structure. For example, ['a', 'b'] will become 0: 'a', 1: 'b' instead of 0.a: 'a', 0.b: 'b'.
overwrite (default: false): If true, existing keys in the flattened object will be overwritten if there are duplicate keys.
maxDepth (default: Infinity): Limits the depth of nested objects to flatten. Setting this to a number (e.g., 2) will only flatten objects up to the second level of nesting.
transformKey (default: (key) => key): A function that allows you to transform keys as they're being flattened. This can be useful for renaming or sanitizing keys.
unflatten(object, options)
Converts a flattened object back into a nested object.
Arguments
object: The flattened object (with dot-separated keys). options (optional): Configuration options (see below). Returns: The unflattened object with nested structures restored.
Available Options: delimiter (default: .): The delimiter used in the flattened object to separate keys.
safe (default: false): If true, the function will avoid merging arrays into objects.
transformKey (default: (key) => key): A function to transform keys as they are unflattened.
Default Options
If you don’t provide any options, the following default settings will be used:
const defaultOptions = {
delimiter: '.',
safe: false,
overwrite: false,
maxDepth: Infinity,
transformKey: (key) => key,
};Contributions
Feel free to submit issues, pull requests, or suggestions! All contributions are welcome.
