@dmarchena/objmapper

1.0.2 • Public • Published

objmapper Build Status Test Coverage Maintainability

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 to keyout (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

Readme

Keywords

Package Sidebar

Install

npm i @dmarchena/objmapper

Weekly Downloads

2

Version

1.0.2

License

MIT

Unpacked Size

10.8 kB

Total Files

9

Last publish

Collaborators

  • dmarchena