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 = {}
for (const key in target) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
result[key] = target[key]
}
}
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
if (typeof source[key] === 'object' && source[key] !== null) {
if (!result[key]) {
result[key] = Array.isArray(source[key]) ? [] : {}
}
result[key] = deepMerge(result[key], source[key])
} else {
result[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 |