Last active
June 6, 2018 02:06
-
-
Save Deele/93c46cd5f0e2633b3732f8030c4294ad to your computer and use it in GitHub Desktop.
Deep extend of JSON-type settings (JS objects) with options (JS objects)
This file contains 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
/** | |
* @param {object} settings | |
* @param {object} options | |
* @returns {object} | |
*/ | |
function updateSettings(settings, options) { | |
var updatedSettings = {}; | |
if (typeof settings !== 'undefined') { | |
Object.assign(updatedSettings, settings); | |
} | |
Object | |
.keys(options) | |
.forEach(function(k) { | |
// Avoid breaking objects, when some JSON encoders parse empty associative arrays as empty numeric arrays | |
if (!( | |
typeof updatedSettings[k] !== 'undefined' && | |
updatedSettings[k] !== null && | |
updatedSettings[k].constructor.name === 'Object' && | |
options[k].constructor.name === 'Array' && | |
options[k].length === 0 | |
)) { | |
updatedSettings[k] = (options[k] !== null && options[k].constructor.name === 'Object' ? | |
updateSettings(updatedSettings[k], options[k]) : | |
options[k] | |
); | |
} | |
}); | |
return updatedSettings; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment