Merges the enumerable properties of two or more objects deeply. Fastest implementation of deepmerge, see section 'Benchmarks'.
Install
npm i @fastify/deepmerge
Usage
The module exports a function, which provides a function to deepmerge Objects.
@fastify/deepmerge does not mutate the input objects. It returns a new object, which is the result of the merge.
deepmerge(options)
options is optional and can contain the following values:
symbols (boolean, optional) - should also merge object keys that are symbols, default is false
all (boolean, optional) - makes deepmerge accept and merge any number of passed objects, default is false
mergeArray (function, optional) - provide a function, which returns a function to add custom array merging function
cloneProtoObject (function, optional) - provide a function, which must return a clone of the object with the prototype of the object
isMergeableObject (function, optional) - provide a function, which must return true if the object should be merged, default is isMergeableObject from this module
onlyDefinedProperties (boolean, optional) - if true, properties with undefined in the source will not overwrite existing values from the target, default is false
To overwrite the default behavior regarding merging Arrays, you can provide a function to the
mergeArray option of the deepmerge-function. The function provided to mergeArray
gets an options-parameter passed, which is an Object containing the following keys and values.
Example 2: Merge each element of the source-Array with the element at the same index-position of the target-Array.
function deepmergeArray(options) { const deepmerge = options.deepmerge const clone = options.clone return function (target, source) { let i = 0 const tl = target.length const sl = source.length const il = Math.max(target.length, source.length) const result = new Array(il) for (i = 0; i < il; ++i) { if (i < sl) { result[i] = deepmerge(target[i], source[i]) }
cloneProtoObject
Merging objects with prototypes, such as Streams or Buffers, are not supported by default.
You can provide a custom function to let this module deal with the object that has a prototype(JSON object excluded).
By default, @fastify/deepmerge merges all objects except native Date and RegExp objects. To exclude certain objects from being merged, you can provide a custom function to the isMergeableObject option.
The default function is exported by this module as isMergeableObject.
The following example shows how to extend the default function to exclude globally defined FormData objects from being identified as mergeable objects.