Skip to content

Instantly share code, notes, and snippets.

@ConradSulzer
Last active January 28, 2021 16:18
Show Gist options
  • Save ConradSulzer/05cc0839816096c3d15bc534f23a7aa3 to your computer and use it in GitHub Desktop.
Save ConradSulzer/05cc0839816096c3d15bc534f23a7aa3 to your computer and use it in GitHub Desktop.
Set nested values in objects
// Use to set nested values in an object. If a property doesn't exist yet in the object it will be created.
//** 'obj' is the obj you want to set the value in, can be an empty object if you want to populate a new one.
//** 'array' is the path to the value. I typically have the path represented as a string
// and get the array from string.split('.'). E.x. array = ['set', 'value', 'here'].
//** 'value' is the value you want to set
const deepSetObj = (obj, array, value) => {
const [head, ...rest] = array
if(rest.length <= 0) {
return obj[head] = value
}else if (obj.hasOwnProperty(head)) {
return deepSetObj(obj[head], rest, value)
}else {
obj[head] = {};
return deepSetObj(obj[head], rest, value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment