Skip to content

Instantly share code, notes, and snippets.

@vitkon
Created May 10, 2017 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitkon/a381ecc10efc66e0fb8212fd64f1c59b to your computer and use it in GitHub Desktop.
Save vitkon/a381ecc10efc66e0fb8212fd64f1c59b to your computer and use it in GitHub Desktop.
Simple object to object mapper
const _ = require('lodash');
class SimpleMapper {
constructor(data) {
this.data = _.cloneDeep(data);
this.mappings = [];
this.result = {};
}
addMapping(destination, source, transform = v => v) {
this.mappings.push({ source, destination, transform });
return this;
}
map() {
this.mappings.forEach(({ destination, source, transform }) => {
const value = _.isFunction(source) ?
source.call(this.data) : _.get(this.data, source);
const transformedValue = _.isFunction(transform) ?
transform.call(this.data, value) : value;
_.set(this.result, destination, transformedValue);
});
return this.result;
}
}
// example
const objA = { prop1: 'John', prop2: 'Smith', prop3: { prop5: '35'} };
const mapper = new SimpleMapper(objA);
const toUpper = v => v.toUpperCase();
function getFullName() {
return `${this.prop1} ${this.prop2}`;
}
const person = mapper
.addMapping('personal.name', 'prop1', toUpper)
.addMapping('personal.fullName', getFullName, toUpper)
.addMapping('age', 'prop3.prop5')
.map();
console.log(person); // => { personal: { name: 'JOHN', fullName: 'JOHN SMITH' }, age: '35' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment