map-json
Library to map objects into a given JSON structure
Installation
Install via npm:
$ npm install map-json
Documentation
Usage
MapJson.map(sourceObject, mappingObject, functionSource?, preProcessFunction?)
Basic Mapping Object Syntax
The mapping object defines the structure of the created JSON object. All objects that contain a _source
tag will be replaced with its respective data from the source object.
Example mapping object:
name: 'John' // This will be kept as is data: id: 123 // This will be kept as is username: _source: 'john.username' // will be replaced with the respective value from the source object
Example source object:
john: username: 'johndoe'
Mapping:
// Using the objects defined aboveMapJson;/*{ name: 'John', data: { id: 123, username: 'johndoe' }}*/
Wildcards
The _source
value can also contain wildcards:
MapJson;/*{ usernames: ['John', 'Peter'], firstUser: 'John'}*/
Default values
_default
can be used to return default values when the referenced value is not defined in the source object:
MapJson;/*{ fruit: 'apple'}*/
Transform functions
By defining _transform
, values can be processed by one or more transform functions:
MapJson;/*{ fruit: 'APPLE'}*/
It is also possible to pass parameters to transform functions or chain them:
MapJson;/*{ fruit: 'APPLE_123'}*/
Conditions
_condition
can be used to only map values when a certain condition is met. The syntax is identical to transform functions. However, instead of the result of the previous function, each transform function always receives the source(s) as the first parameter.
MapJson;/*{ fruitName: 'apple', fruitId: 0, otherFruit: 'banana'}*/
Nested mappings and conditional transforms
MapJson;/*{ fruitName: 'APPLE'}*/
Transform each
Instead of _transform
, it is also possible to use _transformEach
. If the source (or pre-process) resolves to an array, _transformEach
is executed separately for each array value. Note: When _transform
and _transformEach
are defined, _transform
is executed first.
Example of a more advanced mapping with partial array transformation and use of _transformEach
:
MapJson;/*{ fruits: [{ fruitColor: 'r' fruitId: 1 fruitName: 'APPLE' }, { fruitColor: 'y' fruitId: 2 fruitName: 'LEMON' }]}*/
Pre-process function
It is possible to pre-process all mapped values, e.g., for type conversions:
MapJson;/*{ userId: '123'}*/
Note: When using multiple sources, each source is pre-processed separately. However, when a source resolves to an array, the pre-process function will receive the complete array, not separate values.