Allow direct object access in property mapper

master
Sven Slootweg 7 years ago
parent 68da848e76
commit fda5765197

@ -23,14 +23,37 @@ module.exports = function createPropertyMapper(propertyMap) {
destinationProperty: destinationProperty destinationProperty: destinationProperty
} }
} }
}); }).reduce((mappings, item) => {
mappings[item.sourceProperty] = item;
return mappings;
}, {});
return function mapProperties(properties) { return function mapProperties(properties) {
return mappings.map((mapping) => { return Object.keys(properties).map((propertyName) => {
if (properties[mapping.sourceProperty] != null) { let propertyValue = properties[propertyName];
if (propertyName.includes(".")) {
/* Property names with a dot are attempts to directly access an
* object within a composite object; they need to be handled
* specially since they essentially bypass the mapping step.
* If there is *more* than a single dot, then this is an attempt
* to access a *nested* composite object, and therefore we should
* keep the entire property name after the first dot intact. */
let propertyNameSegments = propertyName.split(".");
let destinationObject = propertyNameSegments[0];
let realPropertyName = propertyNameSegments.slice(1).join(".");
return {
sourceProperty: propertyName,
destinationObject: destinationObject,
destinationProperty: realPropertyName,
value: propertyValue
}
} else if (mappings[propertyName] != null) {
return Object.assign({ return Object.assign({
value: properties[mapping.sourceProperty] value: propertyValue
}, mapping); }, mappings[propertyName]);
} }
}).filter((item) => { }).filter((item) => {
return (item != null); return (item != null);
@ -76,7 +99,8 @@ let mapper = module.exports({
console.log(mapper({ console.log(mapper({
foo: "hello one foo!", foo: "hello one foo!",
bar: "hello bar!", bar: "hello two bar!",
twoFoo: "hello two foo!", twoFoo: "hello two foo!",
baz: "hello baz!" baz: "hello baz!",
"one.bar": "hello one bar!"
})); }));

Loading…
Cancel
Save