• Stars
    star
    276
  • Rank 149,319 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Copy properties from one object to another.

object-mapper

Build Status Join the chat at https://gitter.im/wankdanker/node-object-mapper

About

Utility to copy properties from one Object to another based on instructions given in a map Object, which defines which properties should be mapped.

Installation

$ npm install --save object-mapper

Usage

A mapping object key is the source key and the value is the key on the destination object the value is mapped to.

Source

The source key can be specified as a simple string:

{
  "foo": "bar" //map src.foo to dest.bar
}

You may specify properties deep within the source Object to be copied to properties deep within the destination Object by using dot notation in the mapping key:

{
  "foo": "bar.baz", //map src.foo to dest.bar.baz
  "bar.foo": "baz" //map src.bar.foo to dest.baz
}

You may also specify Array lookups within the source Object to be copied to properties deep within the destination object by using [] notation in the mapping:

{
  "[].foo": "bar[]",
  "foo[].bar": "[]",
  "foo[0].bar": "baz"
}

Destination

You may specify the destination as:

  • String
  • Object
  • Array

String

When using a String as the destination, use the method described above.

To utilize a source field more than once, utilize the key-transform syntax in the mapping link:

var objectMapper = require('object-mapper');

var map = {
  "foo": [
    {
      key: "foo",
      transform: function (value) { 
        return value + "_foo";
      }
    },
    {
      key: "baz",
      transform: function (value) {
        return value + "_baz";
      }
    }
  ],
  "bar": "bar"
};

var src = {
	foo: 'blah',
	bar: 'something'
};

var dest = objectMapper(src, map);

// dest.foo: 'blah_foo'
// dest.baz: 'blah_baz'
// dest.bar: 'something' 

Object

Using an Object as the destination:

{
  "key": (String),
  "transform": (Function()),
  "default": (Function()|String|Number)
}
Methods
transform(sourceValue, sourceObject, destinationObject, destinationKey);

Specify the mapping of a sourceValue as you need;

default(sourceObject, sourceKey, destinationObject, destinationKey);

Specify a default return value when the sourceValue is undefined or null.

Array

When using an Array as the destination you can pass a String, an Object or another Array (shorthand for Object):

{
  "foo": ["bar", "baz"],
  "bar": [{
    "key": "foo"
  }],
  "baz": [["bar", null, "foo"]]
}

If you want to append items to an existing Array, append a + after the []

{
  "sourceArray[]": {
    "key": "destination[]+",
    "transform": (val) => mappingFunction(val)
  },
  "otherSourceArray[]": {
    "key": "destination[]+",
    "transform": (val) => mappingFunction(val)
  }
}

// Results in the destination array appending the source values
{
  "destination": [
    {/*Results from the mapping function applied to sourceArray */},
    {/*Results from the mapping function applied to otherSourceArray */},
  ]
}

The Array shorthand for an Object:

[(Key(String))), (Transform(Function())), (Default(String|Number|Function()))]

Null Values

By default null values on the source Object is not mapped. You can override this by including the post fix operator '?' to any destination key.

var original = {
  "sourceKey": null,
  "otherSourceKey": null
}

var transform = {
  "sourceKey": "canBeNull?",
  "otherSourceKey": "cannotBeNull"
}

var results = ObjectMapper(original, {}, transform);

// Results would be the following
{
  canBeNull: null
}

Methods

.merge(sourceObject[, destinationObject], mapObject);

Copy properties from sourceObject to destinationObject by following the mapping defined by mapObject

This function is also exported directly from require('object-mapper') (ie: var merge = require('object-mapper');)

  • sourceObject is the object FROM which properties will be copied.
  • destinationObject [OPTIONAL] is the object TO which properties will be copied.
  • mapObject is the object which defines how properties are copied from sourceObject to destinationObject

.getKeyValue(sourceObject, key);

Get the key value within sourceObject, going deep within the object if necessary. This method is used internally but is exposed because it may be of use elsewhere with other projects.

  • sourceObject is the object from which you would like to get a property/key value.
  • key is the name of the property/key you would like to retrieve.

.setKeyValue(destinationObject, key, value);

Set the key value within destinationObject, going deep within the object if necessary.This method is used internally but is exposed because it may be of use elsewhere with other projects.

  • destinationObject is the object within which the property/key will be set.
  • key is the name of the property/key which will be set.
  • value is the value of the property/key.

Example

var objectMapper = require('object-mapper');

var src = {
  "sku": "12345",
  "upc": "99999912345X",
  "title": "Test Item",
  "description": "Description of test item",
  "length": 5,
  "width": 2,
  "height": 8,
  "inventory": {
    "onHandQty": 12
  }
};

var map = {
  "sku": "Envelope.Request.Item.SKU",
  "upc": "Envelope.Request.Item.UPC",
  "title": "Envelope.Request.Item.ShortTitle",
  "description": "Envelope.Request.Item.ShortDescription",
  "length": "Envelope.Request.Item.Dimensions.Length",
  "width": "Envelope.Request.Item.Dimensions.Width",
  "height": "Envelope.Request.Item.Dimensions.Height",
  "inventory.onHandQty": "Envelope.Request.Item.Inventory"
};

var dest = objectMapper(src, map);

/*
{
  Envelope: {
    Request: {
      Item: {
        SKU: "12345",
        UPC: "99999912345X",
        ShortTitle: "Test Item",
        ShortDescription: "Description of test item",
        Dimensions: {
          Length: 5,
          Width: 2,
          Height: 8
        },
        Inventory: 12
      }
    }
  }
};
*/

Use case

I use the object-mapper's merge() method to map values from records returned from a database into horribly complex objects that will be eventually turned in to XML.

License

The MIT License (MIT)

Copyright (c) 2012 Daniel L. VerWeire

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

node-discover

Automatic and decentralized discovery and monitoring of nodejs instances with built in support for a variable number of master processes, service advertising and channel messaging.
JavaScript
229
star
2

node-function-rate-limit

Rate Limit any Function in node
JavaScript
68
star
3

node-redis-jsonify

Save JSON representation of objects to redis when using node_redis
JavaScript
58
star
4

node-tableify

Create HTML tables from JavaScript Objects
JavaScript
38
star
5

node-datagram-stream

Streaming UDP with bcast, mcast or direct options
JavaScript
32
star
6

node-object-to-xml

Convert any JavaScript object to XML
JavaScript
19
star
7

node-google-checkout

A Google Checkout API implementation for node.js
JavaScript
13
star
8

node-epl

An EPL printer library for nodejs
JavaScript
12
star
9

node-automesh

Automatically discover, connect to and accept TCP connections from other nodes on a subnet.
JavaScript
9
star
10

node-dns-express

An Express style DNS server
JavaScript
9
star
11

node-tracking-url

Get the carrier name and web url for a given tracking number
JavaScript
8
star
12

node-zsync

Synchronize/Replicate ZFS datasets - CLI and API
JavaScript
8
star
13

node-youtube-dl-server

A nodejs based front-end server to youtube-dl
JavaScript
8
star
14

node-usey

Generic middleware/plugin framework inspired by express.js's .use()
JavaScript
7
star
15

node-sftpjs

sftp api similar to mscdex/node-ftp using ssh2
JavaScript
6
star
16

gs1

gs1 checkdigit generation and validation in javascript
JavaScript
6
star
17

node-domain-name-parser

Parse domain name into tld, sld, domain, domainName, host
JavaScript
5
star
18

node-channeladvisor

API wrapper for ChannelAdvisor's SOAP service for node.js
JavaScript
4
star
19

connect-proxy

A simple Connect/Express middleware which proxies a request to another server.
JavaScript
4
star
20

node-unixodbc-isql-json

A hacky solution for querying ODBC data sources (including MS SQL) with nodejs.
C
4
star
21

node-object-mask

Copy an object based on a mask of allowed or denied properties
JavaScript
3
star
22

node-redis-gzip

Magical gzip/gunzip on calls to setz(), getz(), mgetz()
JavaScript
3
star
23

node-write-file-queue

A writeFile queue which reattempts to write after errors occur
JavaScript
3
star
24

symdb

A JSON database that uses symbolic links for indexing
JavaScript
3
star
25

haproxy-upstart-wrapper

A wrapper for haproxy to be used with Upstart
JavaScript
3
star
26

node-redis-index

Index and query arbitrary objects with Redis.
JavaScript
3
star
27

node-odbc-pool

A connection pool for node's ODBC module
JavaScript
3
star
28

web-object

Generic object collections wrapping drag/drop, sorting, filtering, toggle, show, hide functions.
JavaScript
3
star
29

approved-browser

Specify minimum versions of browsers and get accept/reject callbacks on approved/disapproved browsers
JavaScript
3
star
30

simple-vcard

A module to transform simple javascript objects into vCards and vLists
JavaScript
3
star
31

node-trimpath-template

trimpath-template templating language
JavaScript
3
star
32

node-transaction-group

Collect [optionally unique] objects over a period of time and then act on them
JavaScript
2
star
33

node-render-sender

On-demand image resizer/minfier/cacher
JavaScript
2
star
34

node-haproxy-log-parse

Parse haproxy log lines to JavaScript objects
JavaScript
2
star
35

node-proc-pid

Read select "files" from /proc/:pid/*
JavaScript
2
star
36

jquery-scrollify

Make HTML tables scrollable across browsers with jQuery
JavaScript
2
star
37

automesh-dnode

dnode plugin for automesh
JavaScript
2
star
38

webcolumns

A columns/content manipuliation API with drag and drop capability
JavaScript
2
star
39

node-dank-cast

Cast values to more specific types with default values if they can't be casted
JavaScript
2
star
40

node-token-collector

Collect string tokens if they match filters
JavaScript
2
star
41

node-print-url

JavaScript
2
star
42

node-inotify-run

Run scripts on inotify events
JavaScript
2
star
43

node-dank-moveFile

Pure JavaScript moveFile function for node.js
JavaScript
2
star
44

node-array-page

Get a page worth of records from an array
JavaScript
2
star
45

ofapi

Open Forum API for phpBB (XML/JSON-RPC)
PHP
2
star
46

node-layered-hash-table

A hash table made of layers where lower numbered layers over-ride the value of higher layers
JavaScript
2
star
47

node-templater

Template engine abstraction layer
JavaScript
2
star
48

node-find-alternate-file

Given a file path and a list of file extensions, find a file that exists
JavaScript
2
star
49

jquerytablehelper

Automatically exported from code.google.com/p/jquerytablehelper
JavaScript
1
star
50

symdb-rest

A rest interface to multiple symdb databases
JavaScript
1
star
51

greenhorn

A simple server that renders HTML using various engines and a configuration file with test data
JavaScript
1
star
52

node-is-object-empty

Check to see if an object is empty (has or does not have keys)
JavaScript
1
star
53

node-dank-csv

A simple CSV file parser
JavaScript
1
star
54

node-find-alternate-index

Find an index file if path is a directory
JavaScript
1
star
55

node-mutable-array

Mutable Array Functions
JavaScript
1
star
56

sortkeys

Sort the keys of a Javascript Object
JavaScript
1
star
57

node-redis-key

JavaScript
1
star
58

node-dank-do-while

An asynchronous do-while-like function for node.
JavaScript
1
star
59

nnfs

my progress through nnfs.io
JavaScript
1
star
60

node-dank-fileEmitter

Walk a directory and emit events for each object encountered
JavaScript
1
star
61

node-dank-queue

A versatile async flow control module for node
JavaScript
1
star
62

node-dank-copyFile

Pure JavaScript copyFile function for node.js
JavaScript
1
star
63

node-prefetch-cache

A cache store for node that can optionally prefill the cache store
JavaScript
1
star
64

node-image-serve

An HTTP image server that resizes, trims and caches
JavaScript
1
star
65

node-replace-empty-objects

Recursively replace empty objects with null
JavaScript
1
star
66

node-dank-map

A map function for node which can map over anything.
JavaScript
1
star
67

jsinclude

Load js and css files programatically in the browser at run-time.
JavaScript
1
star
68

freetds

C
1
star
69

node-object-array

Add array-like functionality to objects while using unique ids instead of numeric indexes
JavaScript
1
star
70

node-array-index

Create indexes based on arrays of objects
JavaScript
1
star
71

node-cachier

Caching with various backends
JavaScript
1
star
72

node-experiments

This is a repository of random node experiments I have done.
JavaScript
1
star
73

node-postal-io

A nodejs client for Postal
JavaScript
1
star
74

node-depresol

An asynchronous dependency resolver for node
JavaScript
1
star
75

node-dank-amap

An asynchronous map function which can map over anything for node.
JavaScript
1
star
76

node-usey-http

An express clone with usey at its core
JavaScript
1
star
77

node-cross-mash

Create a single object from an array of objects based on specified usage keys
JavaScript
1
star
78

event-pipeline

A simple event emitter which processes events in order
JavaScript
1
star
79

node-aloof

Filter Arrays of Objects
JavaScript
1
star
80

node-dropkey

From each object in an array, delete keys specified
JavaScript
1
star