deeply

Universal (nodejs + browser) library that deeply merges properties of the provided objects, returns untangled copy (clone). Mutable operations also available.

Deeply

Universal (nodejs + browser) library that deeply merges properties of the provided objects, returns untangled copy (clone). Mutable operations also available.

Version 1.0.0 backwards compatible with 0.1.0 version.

$ npm install deeply --save

– Deeply merges two or more objects.

var merge = require('deeply');
 
var clone = merge({a: {a1: 1}}, {a: {a2: 2}});
 
assert.deepEqual(clone, {a: {a1: 1, a2: 2}});

– As degenerated case of merging one object on itself, it's possible to use deeply as deep clone function.

var merge = require('deeply');
var clone = merge;
 
var x = {a: {b: {c: 1}}};
var y = clone(x);
 
y.a.b.= 2;
 
assert.deepEqual(x.a.b.c, 1);

– By default array treated as primitive values and being replaced upon conflict, for more meaningful array merge strategy, provide custom reduce function as last argument.

var merge = require('deeply');
var clone = merge({ a: { b: [0, 2, 4] }}, { a: {b: [1, 3, 5] }});
 
assert.deepEqual(clone, { a: { b: [1, 3, 5] }});
var merge = require('deeply');
 
function customMerge(ab)
{
  return (a||[]).concat(b);
}
 
var clone = merge({ a: { b: [0, 2, 4] }}, { a: {b: [1, 3, 5] }}, customMerge);
 
assert.deepEqual(clone, { a: { b: [0, 2, 4, 1, 3, 5] }});
var merge = require('deeply/mutable');
var myObj = {a: {a1: 1, a2: 2}, b: {b1: 11, b2: 12}};
 
merge(myObj, {c: 'c', d: 'd'}, {x: {y: {z: -Infinity}}});
 
assert.deepEqual(myObj, {a: {a1: 1, a2: 2}, b: {b1: 11, b2: 12}, c: 'c', d: 'd', x: {y: {z: -Infinity}}});

More examples can be found in test/index.js.

Deeply is licensed under the MIT license.