Last active
January 28, 2021 16:18
-
-
Save ConradSulzer/05cc0839816096c3d15bc534f23a7aa3 to your computer and use it in GitHub Desktop.
Set nested values in objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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