full-merge
v1.0.5
Published
Merge two JavaScript objects deeply (recursively) using sensible rules
Downloads
3
Readme
full-merge
Merge two JavaScript objects deeply (recursively) using sensible rules.
Signature
fullMerge(target: any, source:any): any
Merging Rules
- If an element at the same key is present for both target and y, the value from y will appear in the result.
- Unlike many merge utilities, null and undefined values do not overwrite existing values.
- If either source or target (or both) are primitive values, source overwrites target.
- Arrays are NOT merged; a source array value will overwrite a taget value with the same key
- Circular references are supported.
- Both target and source are considered immutable, so neither are modified.
- The returned value is always a based on a deep clone of the input values
Example
var fullMerge = require('full-merge')
var src = {
foo: null,
bar: {
b: 1,
a: true,
r: new Date()
},
arr: [],
extra: 0 // new property not declared in target; will be included in result
};
var tgt = {
foo: 'foo', // value will be preserved since src.foo is null
bar: 3, // value is overwritten by src.bar object
arr: [1, 2, 3], // will be overwritten by src.arr empty array
rgx: /.*/g // will be preserved since src.rgx is not declared
};
RegExp.prototype.toJSON = RegExp.prototype.toString;
console.log(JSON.stringify(fullMerge(tgt, src)));
Output:
{
"foo": "foo",
"bar": {
"b": 1,
"a": true,
"r": "2016-07-19T20:22:51.264Z"
},
"arr": [],
"rgx": "/.*/g",
"extra": 0
}
Install
npm install full-merge --save