reduce | const deepMerge = (target, source) => {
return Object.keys(source).reduce((result, key) => {
if (Object.prototype.hasOwnProperty.call(source, key)) {
result[key] = typeof source[key] === 'object' && source[key] !== null
? deepMerge(result[key] ?? {}, source[key])
: source[key]
}
return result
}, { ...target })
}
const english = {
'key1': 'Hello',
'key2': {
'key3': 'Welcome here',
'key4': 'optional item',
'key5': {
'key6': 'another level of nesting'
}
}
}
const french = {
'key1': 'Bonjour',
'key2': {
'key3': 'Bienvenue'
}
}
deepMerge(english, french)
| ready |
for loop | const deepMerge = (target, source) => {
const result = { ...target }
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
result[key] = typeof source[key] === 'object' && source[key] !== null
? deepMerge(result[key] ?? {}, source[key])
: source[key]
}
}
return result
}
const english = {
'key1': 'Hello',
'key2': {
'key3': 'Welcome here',
'key4': 'optional item',
'key5': {
'key6': 'another level of nesting'
}
}
}
const french = {
'key1': 'Bonjour',
'key2': {
'key3': 'Bienvenue'
}
}
deepMerge(english, french)
| ready |