wankdanker / node-object-mapper

Copy properties from one object to another.
MIT License
277 stars 73 forks source link

Adding syntax support for destination->source #45

Open MxAshUp opened 7 years ago

MxAshUp commented 7 years ago

Background I often use Object Mapper to create objects that fit a particular schema. When I manage my authored code, I want to clearly see the schema of the object I am creating. With Object Mapper using source->destination to map fields, it is sometimes difficult to infer what the resulting object might look like.

Example let's say I'm mapping a single field from one object to multiple fields in my destination object.

objectMapper(data, {
  'phoneNumber': ['primaryPhone', 'mobilePhone']
});
// Outputs something like:
{
  primaryPhone: '555-555-5555',
  mobilePhone: '555-555-5555'
}

Glancing at the code above, it's not immediately clear what the destination object will look like.

Proposed Feature Let's say Object Mapper could map with reverse syntax (destination->source). For example:

objectMapper(data, {
  'primaryPhone': 'phoneNumber',
  'mobilePhone': 'phoneNumber'
});

Now it's pretty clear what the destination object will potentially look like. This would also give headway to map fields that don't have sources. For example:

objectMapper(data, {
  'hasPhoneNumber': {default: true} // source object doesn't have value for this property, but we always want it to be mapped to true
});

Forwards Compatibility If implemented, it would be silly to make this the default behavior since all code would break. But perhaps this could be an optional parameter or different module that's imported.

objectMapperDestinationSource = require('object-mapper').destinationSource;
// Or...
objectMapper = require('object-mapper');
objectMapper( data, map, [reverseMap = false]);

Feedback I am not confident that this would be an appropriate feature to add, or if it would conflict with direction of the project. But I wanted to explore the idea if anyone else has had similar thoughts.