Created
May 10, 2017 23:41
-
-
Save vitkon/a381ecc10efc66e0fb8212fd64f1c59b to your computer and use it in GitHub Desktop.
Simple object to object mapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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