bimedia-objectmapper

object mapper for node

bimedia-objectmapper

object mapper for node

This module allow to map keys and values from an object to an other. Mapping uses a tranformation rules. There are 3 transformation rules types :

  • identity : copy the attribute and value to the target object.
  • alias : rename the attribute in the target object (value is unchanged).
  • complex : apply tranformation rule provided to change attribute name and value.

npm install --save bimedia-objectmapper

var ObjectMapper = require('bimedia-objectmapper');
var mapper = objectMapper({'key':'clé'});
var result = mapper({key:'value'});
// {'clé': 'value'} 
var objectMapper = require('bimedia-objectmapper'), 
  fs = require('fs'), 
  JSONStream = require('JSONStream');
  
var mapper = objectMapper(rules);
fs.createReadStream('package.json')
  .pipe(JSONStream.parse())
  .pipe(mapper.stream())
  .pipe(process.stdout);
var objectMapper = require('bimedia-objectmapper');
var mapper = objectMapper({'key':'clé'});
var sources = [{key:'value1'}, {key:'value2'}, {key:'value3'}];
var result = sources.map(mapper);
//[ { 'clé': 'value1' }, 
//  { 'clé': 'value2' }, 
//  { 'clé': 'value3' } ] 

No specific rule is needed. Attribute is copied to target object.

Declare a constant as attribute value. Example :

var rules = {
    "trxpvptpv": "trxid"
};

This rule renames trxpvptpv attribute in source object, to trxid in target object.

Define an object matching the source attribute. Example :

var rules = {
     'state' : {
        name : 'currentState',
        mapper : function (val) {
            if (val == 'Y') {
                return 'REFUNDED';
            }
            return val == 'N' ? 'REFUSED' : 'PENDING';
        }
    }
};

Or directly with a function :

var rules = {
     'state' : function (kv) {
            var value;
            if (val == 'Y') {
                value =  'REFUNDED';
            }
            value = val == 'N' ? 'REFUSED' : 'PENDING';
            return {key: 'currentState', value: value};
        }
    }
};

This 2 examples transforms the state attribute in source object to an currentState attribute in target object.

Mapping can be customize with the second argmuent of ObjectMapper : For instance to disable identity mapping by default :

var mapper = ObjectMapper(rules, {defaults: false});

Or to specify a default mapping function :

var mapper = ObjectMapper(rules, {defaults: ObjectMapper.keys.camelCase});
  • defaults : (function | boolean) define a default mapping function. By defaut ObjectMapper.identity.