I am trying to create a function that takes a target json object a source json object (the update)
The rule is that the target must be updated by the source.
If the key are the same, the value of the target is overwritten.
If the key contains a dot . we consider it as a nested update (example 3)
If the update key does not exist in the target, we create it.
Example 1:
var target = {
foo: 1,
}
var source = {
foo: 22,
}
var output = {
foo: 22
}
Example 2:
var target = {
foo: {
bar: 1
},
}
var source = {
foo: {
baz: 999
},
}
var output = {
foo: {
baz: 999
}
}
Example 3:
var target = {
foo: {
bar: 1,
baz: 99,
},
}
var source = {
'foo.bar': 22,
}
var output = {
foo: {
bar: 22,
baz: 99
}
}
Example 4 (Array)
We assume that numbers are invalid key for the source. For example, the below source will never occur
// this will never happen
let source = {
1: 'something'
}
However, update can update the value of an array at a specif index using the dot . method
const source = {
foo: [0, 1,2,3, {four: 4}]
}
const target = {
'foo.0': 'zero',
'foo.4.four': 'four',
'foo.4.five': 5,
}
const output = {
foo: ['zero', 1, 2, 3, {four: 'four', five: 5}]
}
Hence array can not change in size using the dot update, to change the size, we need to overwrite the entire array
My function below works perfectly fine with the Example 1 but I cannot get it to work with example 2 and 3.
Instead I obtain:
var example2 = {
bar: 1,
baz: 999,
}
var example3 = {
foo: {
bar: 1,
baz: 99,
},
'foo.bar': 22,
}
function deepMerge(target, source) {
Object.entries(source).forEach(([key, value]) => {
if (value && typeof value === 'object') {
deepMerge(target[key] = target[key] || {}, value);
return;
}
target[key] = value;
});
return target;
}
barin example #2?sourcehas dotted keys, correct?sourcelikefoo.bar[0].baz?