#2755
Medium JavaScript Deep merge of two objects
64.4% acceptance
Mar 31, 2026
15
4
Given two values obj1 and obj2, return a deepmerged value.
Values should be deepmerged according to these rules:
If the two values are objects, the resulting object should have all the keys that exist on either object. If a key belongs to both objects, deepmerge the two associated values. Otherwise, add the key-value pair to the resulting object.
If the two values are arrays, the resulting array should be the same length as the longer array. Apply the same logic as you would with objects, but treat the indices as keys.
Otherwise the resulting value is obj2.
You can assume obj1 and obj2 are the output of JSON.parse().
Solution
TypeScript
Time O(n)
Space O(1)
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
function deepMerge(obj1: JSONValue, obj2: JSONValue): JSONValue {
if (obj1 === null || obj2 === null || typeof obj1 !== 'object' || typeof obj2 !== 'object') return obj2;
if (Array.isArray(obj1) !== Array.isArray(obj2)) return obj2;
const result: any = Array.isArray(obj1) ? [...obj1] : { ...obj1 };
for (const key of Object.keys(obj2)) {
if (key in result) {
result[key] = deepMerge(result[key], (obj2 as any)[key]);
} else {
result[key] = (obj2 as any)[key];
}
}
return result;
};
/**
* let obj1 = {"a": 1, "c": 3}, obj2 = {"a": 2, "b": 2};
* deepMerge(obj1, obj2); // {"a": 2, "c": 3, "b": 2}
*/