0.1.2 • Published 7 years ago

wrangler-object-mapper v0.1.2

Weekly downloads
4
License
ISC
Repository
github
Last release
7 years ago

Wrangler

A simple Javascript object mapper.

Why?

Sometimes you receive onjects that don't quite conform to your standards. Maybe it's naming conventions, or a lack of nested properties. Or maybe you need to transform the object's values in some way. Perhaps you need to parse JSON from an API into your own schema.

Wrangler helps you with this. By defining a map and passing an object, Wrangler whips your objects into shape.

Installation

Just install Wrangler from npm...

npm install wrangler-object-mapper --save

... and import. const Wrangler = require('wrangler-object-mapper')

Getting Started

Wrangler applies tranformations between a source object and a destination object. To create a transformation, define a map:

let map = [
    ['sourceProp', 'destProp']
]

A map is an array of pairs. The left side is the name of a key inside the source object. The right side is the desired name of the source key value will be mapped to in the destination object.

A function may also be passed to either side of the pair.

The left side function signature:

function(source) {}

Where source is the source object. To pass data from the source to the destination object, you must return a value.

The right side function signature:

function(dest, val) {}

Where dest is the destination object and val is the value returned from the source object. You must assign the value to the destination object yourself if using a function.

Example

// The source object
let obj = {
    aPropA: true,
    aPropB: false,
    aPropC: 'FALSE',
    nested: {
        prop: 22
    }
}

// Define a map
let map = [
    // Mapping from flat property name to nested.
    ['aPropA': 'aProp.A'],
    ['aPropB: 'aProp.B'],

    // Mapping from nested property to flat.
    ['nested.prop', 'unnestedNum']

    // Transforming a value and mapping to nested.
    [source => { return !(source.aPropC === 'FASLE')}, 'aProp.C']

    // Transforming value in destination
    ['nested.prop', (dest, val) => { dest['transformed'] == val * 2 }]
]

let result = Atlas.parse(obj, map);

Result:

{
    aProp: {
        A: true,
        B: false,
        C: false
    },
    unnestedNum: 22,
    transformed: 44
}