add function to assign to nested objects with fallbacks

This commit is contained in:
joshuaboud 2022-05-26 14:46:43 -03:00
parent f94edd5b8e
commit ada824fd8e
No known key found for this signature in database
GPG Key ID: 17EFB59E2A8BF50E

View File

@ -0,0 +1,22 @@
const isObject = (obj) => typeof obj === 'object' && !Array.isArray(obj) && obj !== null;
/**
* Assign target to source with Object.assign(), filling in any missing properties from defaults
*
* @param {Object} target - target object
* @param {Object} source - source object
* @param {Object} defaults - fallback values if source is missing any properties
* @returns {Object} - the target object
*/
function assignObjectRecursive(target, source, defaults = {}) {
Object.assign(target, defaults, source);
for (const key in defaults) {
if (isObject(defaults[key]) && isObject(source[key])) {
target[key] = {};
assignObjectRecursive(target[key], source[key], defaults[key]);
}
}
return target;
}
export default assignObjectRecursive;