Skip to content

Instantly share code, notes, and snippets.

@artemsites
Last active June 5, 2024 11:03
Show Gist options
  • Save artemsites/d7f8f8b8e01beb69b8f13f02e5ae99c4 to your computer and use it in GitHub Desktop.
Save artemsites/d7f8f8b8e01beb69b8f13f02e5ae99c4 to your computer and use it in GitHub Desktop.
// @ts-check
/**
* @export
* @param {object} targetObj
* @param {array} arPathAndValue
*
* @example objectUpdateNested(menuChoicesLS, [ this.groupId, this.programId, weekday, type, String(alt) ])
*/
export function objectUpdateNested(targetObj, arPathAndValue) {
let current = targetObj;
const value = arPathAndValue.pop();
for (let i = 0; i < arPathAndValue.length - 1; i++) {
if (typeof current[arPathAndValue[i]] !== 'object' || current[arPathAndValue[i]] === null) {
current[arPathAndValue[i]] = {};
}
current = current[arPathAndValue[i]];
}
current[arPathAndValue[arPathAndValue.length - 1]] = value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment