Skip to content

Instantly share code, notes, and snippets.

@rjdmacedo
Created November 8, 2019 11:25
Show Gist options
  • Save rjdmacedo/4d4ecab568020983b33e242917720e64 to your computer and use it in GitHub Desktop.
Save rjdmacedo/4d4ecab568020983b33e242917720e64 to your computer and use it in GitHub Desktop.
/**
* Assigns to a given base object on the provided path the value.
*
* @example
* assign({}, 'consent.advertising', true) = {
* value: true,
* updatedAt: Date.now()
* }
* @param obj {Object} - Base object that will hold the value.
* @param path {string} - Path to be created, if non existent, on the base object. Format is § string using the dot notation.
* @param value {*} - Value to assign. Can be of any type.
* @returns {boolean} - If the operation is successful returns true.
*/
function assign(obj, path, value) {
try {
var paths = path.split(".");
var lastKeyIndex = paths.length - 1;
for (var i = 0; i < lastKeyIndex; ++i) {
var key = paths[i];
if (!(key in obj)) {
obj[key] = {};
}
obj = obj[key];
}
obj[paths[lastKeyIndex]] = value;
return true;
} catch (e) {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment