@dmarchena/objmapper
v1.0.2
Published
Create a function to transform an object into another one
Downloads
2
Readme
objmapper
Create a function to transform an object into another one.
Installation
Via npm:
npm i -S @dmarchena/objmapper
API
objmapper(transformations)
Returns a function (object) => transformedObject
which accepts an object as parameter and that will return a new one with the transformations applied.
transformations
Type: Object|Object[]
Transformation object format:
{
key: String|String[],
transform: Function,
keyout: String|String[],
}
key
: Key names to retrieve their values and pass them to transform function or directly tokeyout
(renaming).transform
[optional]: Function to transform the values from specified keys.keyout
[optional]: Keys where store the resulting values.
Usage
This tool is written in ES2015, so you can import it as a standard module:
import objmapper from '@dmarchena/objmapper';
Renaming
import objmapper from '@dmarchena/objmapper';
const om = objmapper({
key: ['name', 'surname'],
keyout: ['fistname', 'lastname'];
});
const result = om({
name: 'Alice',
surname: 'Cooper'
}); // { firstname: 'Alice', lastname: 'Cooper' }
Transforming
import objmapper from '@dmarchena/objmapper';
const om = objmapper([{
key: 'name',
transform: str => str.toLowerCase(),
}, {
key: 'surname',
transform: str => str.toUpperCase(),
}]);
const result = om({
name: 'Alice',
surname: 'Cooper'
}); // { name: 'alice', surname: 'COOPER' }
Combining two keys into one
If you declare different keyout
, original keys will be deleted.
import objmapper from '@dmarchena/objmapper';
const om = objmapper([{
key: ['name', 'surname'],
transform: (name, sname) => `${name} ${sname}`,
keyout: 'fullname',
}]);
const result = om({
name: 'Alice',
surname: 'Cooper'
}); // { fullname: 'Alice Cooper' }
License
MIT © David Marchena