Skip to content

Instantly share code, notes, and snippets.

@Deele Deele/updateSettings.js
Last active Jun 6, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.