dtl-js
Version:
Data Transformation Language - JSON templates and data transformation
89 lines (64 loc) • 2.24 kB
Markdown
in DTL is designed for merging a flattened object into a deeply nested object. It facilitates the precise addition or modification of data within complex data structures.
```plaintext
inject($object $flattened_object)
```
- `$object`: The original object into which data will be injected.
- `$flattened_object`: An object with keys in dot notation representing the paths for injection.
### Details
`inject()` takes two parameters: the original object and a flattened object. The flattened object's keys should use dot notation to specify where the values need to be placed in the original object. If the path specified by a key does not exist in the original object, `inject()` will create the necessary nested structures (objects or arrays) to accommodate the value.
### Example
Given an object:
```json
{
"user": {
"name": "John",
"age": 30
}
}
```
And a flattened object:
```json
{
"user.address.street": "123 Main St",
"user.age": 31
}
```
Using `inject()`:
```javascript
const originalObject = {
"user": {
"name": "John",
"age": 30
}
};
const flattenedObject = {
"user.address.street": "123 Main St",
"user.age": 31
};
const transform = {
"out": "(: inject(originalObject flattenedObject) :)"
};
const result = DTL.apply({ originalObject, flattenedObject }, transform);
```
Results in:
```json
{
"user": {
"name": "John",
"age": 31,
"address": {
"street": "123 Main St"
}
}
}
```
- **Overwriting Data**: If a key in the flattened object matches an existing path in the original object, the existing data will be overwritten.
- **Arrays Handling**: Numeric keys in paths lead to the creation of arrays if no existing object is found. Using a '+' symbol appends the value to an existing array.
- The `inject()` function does not modify the original object; it returns a new object with the merged data.
- It is ideal for scenarios where you need to add or update data in a deeply nested structure without altering the entire object.
- Care should be taken with key paths to ensure they accurately reflect the intended structure of the resulting object.
The `inject()` function