deepMerge

is compatible to call with Array

Definition

function deepMerge(...other: object[]) : object;

Example

Okay you want this, we want to go ballsdeep and merge multiple key-value objects while also preserving and merging nested objects within those object.

import '@marthvon/protopp';
// or
import '@marthvon/protopp/objectpp/methods/deepMerge.js';

const a = {
x: {
i: 10
},
y: 0,
z: 1
};

const b = {
w: -1,
x: {
j: 9
}
};

const c = {
z: 2,
};


console.log(a.deepMerge(b));
// Outputs { w: -1, x: { i: 10, j: 9 }, y: 0, z: 1 }
// Note: how nested objects can get merged

// See the two below, order matters with the results when calling merge
console.log(a.deepMerge(c));
// Outputs { x: { i: 10 }, y: 0, z: 2 }
console.log(c.deepMerge(a));
// Outputs { x: { i: 10 }, y: 0, z: 1 }

// The key-value of the right hand side overrides the values of the left-side

Overall, this is more costly than performing a shallow merge as it scales based on the object's depth, like so:

// How to perform shallow copy merge
{ ...a, ...b }
// Outputs { w: -1, x: { j: 9 }, y: 0, z: 1 }
Note: how it doesn't merge nested objects, instead overrides it with the right most value

Lastly, Arrays can be merged with Objects. It uses the Array's indexes as keys. It's important to note of this behaviour

const a = [ 'a', 'b', 'c' ];
const o = {
a: 1,
b: 2,
c: 3
};

console.log(o.deepMerge(a));
// Outputs { a: 1, b: 2, c: 3, 0: a, 1: b, c:3 }
NPM Homepage
Github Homepage
About Me