Created
March 29, 2024 15:32
-
-
Save blizzardengle/a394d25f74ee9f03c99e99f7eb0d8a68 to your computer and use it in GitHub Desktop.
Deep merge two object together. Built this with AI and have no use for it anymore keeping around just in case.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Deep merge two objects together keeping unique keys from each object. | |
* | |
* @param {object} mergeIntoObj - The object to merge another object into. | |
* @param {object} mergeAndPrioritizeObj - The object to merge into mergeIntoObj. This object | |
* has priority when collisions occur. | |
* @returns | |
*/ | |
const deepMerge(mergeIntoObj, mergeAndPrioritizeObj) => { | |
const isPlainObject = (value) => value && typeof value === 'object' && value.constructor === Object; | |
// Recursively merge plain objects and arrays. | |
const merge = (a, b) => { | |
for (const key in b) { | |
if (isPlainObject(a[key]) && isPlainObject(b[key])) { | |
merge(a[key], b[key]); | |
} else { | |
// eslint-disable-next-line no-param-reassign | |
a[key] = b[key]; | |
} | |
} | |
}; | |
// Clone first object to target. | |
const merged = { ...mergeIntoObj }; | |
// Merge objects recursively. | |
merge(merged, mergeAndPrioritizeObj); | |
return merged; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment