Declare Rules to transform flat JS object into another flat JS object. Useful for simple transformations between internal state objects and server requests/responses.
Rules is an object with property names equals to the target property name, and the value is one of:
- String - then it is considered the property name of the source object, and should be copied into the target as is to specified target property (same as rule's name).
- Function - then this function will be applied to the source object and optional property name, and the result will be assigned to the target's property (same as rule's name).
- TODO: null|undefined - just copy the value from the same source's property.
The lib exports transformerFactory by default, which allows partial application. I.e. it takes Rules, and returns a Converter, that expects only Source object.
In addition, ordinary transformer could be imported by name. It expects both Rules and Source objects as arguments.
Import module functions from src directory of the package, instead of a default (which is compiled to ES5 version inside dist directory)
// const transformerFactory = require('simple-object-transformer').transformerFactory;
import { transformerFactory } from 'simple-object-transformer';
const RULES = Object.freeze({
id: 'productId',
name: 'firstName',
fullName: (context) => `${context.firstName} ${context.lastName}`,
});
const SOURCE = Object.freeze({
productId: 123,
firstName: 'John',
lastName: 'Doe',
trash: 555,
});
// create a transformer based on the rules, specified as argument
const transformer = transformerFactory(RULES);
const target = transformer(SOURCE);
console.log(target); // { id: 123, name: 'John', fullName: 'John Doe' }
For more examples see tests.
To use it as a library you should add "stage-0" preset to your babel configuration, because of object destructuring being used in the code. Also you need babel's transform-flow-strip-types plugin as the code uses flowtype.
- implement 'undefined' rule.
Eldar A. eldar.aliyev8@gmail.com