optional set of merging rules.
deep
will deep merge objects. This is the default merging strategy of
objects. It's possible to provide a set of rules to override the merge
strategy for some properties. See merge.
Merge strategy for arrays of objects, deep merging objects having the same
mergeKey
.
key used to identify the same object.
optional set of rules to merge each object.
Example:
import { merge, deep, deepWithKey } from '@jkcfg/std/merge';
const pod = {
spec: {
containers: [{
name: 'my-app',
image: 'busybox',
command: ['sh', '-c', 'echo Hello Kubernetes!'],
},{
name: 'sidecar',
image: 'sidecar:v1',
}],
},
};
const sidecarImage = {
spec: {
containers: [{
name: 'sidecar',
image: 'sidecar:v2',
}],
},
};
merge(pod, sidecarImage, {
spec: {
containers: deepWithKey('name'),
},
});
Will give the result:
{
spec: {
containers: [
{
command: [
'sh',
'-c',
'echo Hello Kubernetes!',
],
image: 'busybox',
name: 'my-app',
},
{
image: 'sidecar:v2',
name: 'sidecar',
},
],
},
}
Merge strategy merging two values by selecting the first value.
Example:
let a = {
k0: 1,
o: {
o0: 'a string',
},
};
let b = {
k0: 2,
k1: true,
o: {
o0: 'another string',
},
};
merge(a, b, { o: first() });
Will give the result:
{
k0: 2,
k1: true,
o: {
o0: 'a string',
},
}
Merges b
into a
with optional merging rule(s).
Base value.
Merge value.
Set of merge rules.
merge
will recursively merge two values a
and b
. By default:
a
and b
are primitive types, b
is the result of the merge.a
and b
are arrays, b
is the result of the merge.a
and b
are objects, every own property is merged with this very
set of default rules.if a
and b
have different types, merge
will throw an error.
Examples:
Merge primitive values with the default rules:
merge(1, 2);
> 2
Merge objects with the default rules:
const a = {
k0: 1,
o: {
o0: 'a string',
},
};
let b = {
k0: 2,
k1: true,
o: {
o0: 'another string',
},
}
merge(a, b);
>
{
k0: 2,
k1: true,
o: {
o0: 'another string',
}
}
Merge strategies
It's possible to override the default merging rules by specifying a merge strategy, a function that will compute the result of the merge.
For primitive values and arrays, the third argument of merge
is a
function:
const add = (a, b) => a + b;
merge(1, 2, add);
> 3
For objects, each own property can be merged with different strategies. The
third argument of merge
is an object associating properties with merge
functions.
// merge a and b, adding the values of the `k0` property.
merge(a, b, { k0: add });
>
{
k0: 3,
k1: true,
o: {
o0: 'another string',
}
}
Merge strategy merging two values by selecting the second value.
Example:
let a = {
k0: 1,
o: {
o0: 'a string',
o1: 'this will go away!',
},
};
let b = {
k0: 2,
k1: true,
o: {
o0: 'another string',
},
};
merge(a, b, { o: replace() });
Will give the result:
{
k0: 2,
k1: true,
o: {
o0: 'another string',
},
}
Merge strategy deep merging objects.