UNPKG

dtl-js

Version:

Data Transformation Language - JSON templates and data transformation

41 lines (23 loc) 2.74 kB
# flatten( $array_or_object [ $separator ] [ $prefix ] ) Flattens a nested array or object into a single-level structure. For arrays, it merges nested arrays into a single array with depth-first values. For objects, it creates a new object with keys representing the full path in dot-notation or a custom separator. - When applied to an array, it is a lossy operation, as it discards information about the original nested array structure. - When applied to an object, the operation is non-lossy, as the resulting object's keys represent the full path to each value, allowing for a full reconstruction of the original object using `unflatten()`. ## Returns: A single-level array or object that represents the original nested structure. ## Parameters: - `$array_or_object`: The array or object to flatten. - `$separator` (optional): The string to use as a separator in place of the default dot (`.`) for object keys. - `$prefix` (optional): A string to prepend to each top-level key in the resulting object. ## Examples: - `flatten([[1 2] [3 [4 5]]])` will produce `[1 2 3 4 5]`. - `flatten({ [ "a" { [ "b" 1 ] } ] [ "c" 2 ] } '-')` will result in `{ "a-b": 1, "c": 2 }`. ## Usage Notes: - When flattening arrays, be aware that the structure of the original array will not be preserved, which means that the process is irreversible. - When flattening objects, the process keeps the structure's integrity through the key paths, making it possible to reconstruct the original object layout with `unflatten()`. - The `$separator` parameter can be used to customize the key path delimiter in the flattened object, which can be helpful when dot-notation is not suitable or may conflict with keys that contain dots. - The `$prefix` parameter allows for the addition of a consistent starting point to each key, which can be useful for namespace differentiation or when integrating with systems that require a certain key structure. ## Advanced Tips: - Be cautious when flattening objects that already contain keys with your chosen separator, as this can cause conflicts or unexpected results. - If you're flattening objects to be used in environments that do not support nested objects (like certain databases), `flatten()` can be a powerful tool to convert complex structures into a compatible format. - Use `flatten()` in combination with `unflatten()` to transform objects for transportation or storage in flat structures, then reassemble them into their original form on the receiving end. Remember that `flatten()` simplifies data handling by reducing the dimensionality of the data, but the trade-offs between lossy (for arrays) and non-lossy (for objects) transformations should be carefully considered based on your use case.