|
| 1 | +export const mergeObjects = ( |
| 2 | + obj1: Record<string, unknown>, |
| 3 | + obj2: Record<string, unknown> = {} |
| 4 | +): Record<string, unknown> => { |
| 5 | + // create a new object that will be the merged version of obj1 and obj2 |
| 6 | + const mergedObj: Record<string, unknown> = {}; |
| 7 | + |
| 8 | + // loop through all the keys in obj1 |
| 9 | + for (const key of Object.keys(obj1)) { |
| 10 | + // if the key is not present in obj2, or if the value at that key is not an object, |
| 11 | + // add the key-value pair to the merged object |
| 12 | + if (!obj2.hasOwnProperty(key) || typeof obj1[key] !== 'object') { |
| 13 | + mergedObj[key] = obj1[key]; |
| 14 | + } else { |
| 15 | + // if the value at the key in obj1 is an object and the same key exists in obj2, |
| 16 | + // merge the objects and add the merged object to the mergedObj |
| 17 | + mergedObj[key] = mergeObjects( |
| 18 | + obj1[key] as Record<string, unknown>, |
| 19 | + obj2[key] as Record<string, unknown> |
| 20 | + ); |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + // loop through all the keys in obj2 |
| 25 | + for (const key of Object.keys(obj2)) { |
| 26 | + // if the key is not present in obj1 or if the value at that key is not an object, |
| 27 | + // add the key-value pair to the merged object |
| 28 | + if (!obj1.hasOwnProperty(key) || typeof obj2[key] !== 'object') { |
| 29 | + mergedObj[key] = obj2[key]; |
| 30 | + } else { |
| 31 | + // if the value at the key in obj2 is an object and the same key exists in obj1, |
| 32 | + // merge the objects and add the merged object to the mergedObj |
| 33 | + mergedObj[key] = mergeObjects( |
| 34 | + obj1[key] as Record<string, unknown>, |
| 35 | + obj2[key] as Record<string, unknown> |
| 36 | + ); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return mergedObj; |
| 41 | +}; |
0 commit comments