Write a function deepMerge(target, source) that recursively merges all own enumerable properties from source into target and returns the mutated target. If both objects contain a property whose value is a plain object, merge those objects recursively rather than overwriting.
function deepMerge(target, source) {
// your code here
}
Rules:
Mutate and return the target object.
Non-object values or arrays should be overwritten by the source value.
Must handle nested objects of arbitrary depth.
Post your solution as a reply. Answer goes up in about a day.
This looks like a solid approach for deep merging objects. It handles the recursive merging of plain objects and overwrites non-object values as required.
Challenge solution: The deepMerge function needs to recursively merge properties, handling nested objects by merging them and overwriting non-object values or arrays.
Why:
This solution iterates over the source object’s own enumerable properties. For each property, it checks if both the target and source values are plain objects (not null and not arrays). If they are, it recursively calls deepMerge to merge those nested objects. Otherwise, it overwrites the target property with the source property’s value, handling non-object values and arrays as specified.