Skip to content

Instantly share code, notes, and snippets.

@Deele
Last active June 6, 2018 02:06
Show Gist options
  • Save Deele/93c46cd5f0e2633b3732f8030c4294ad to your computer and use it in GitHub Desktop.
Save Deele/93c46cd5f0e2633b3732f8030c4294ad to your computer and use it in GitHub Desktop.
Deep extend of JSON-type settings (JS objects) with options (JS objects)
/**
* @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