Create an object by path in JavaScript
If you've ever dug into more complex usage of mkdir
on any Unix flavor, you've probably used the -p
option before. It allows you to create a deep path with only one command. Say you wanted to make a directory at /tmp/1/2/3/
but none of those folders existed, you would have to do something mkdir /tmp && mkdir /tmp/1/ ...
without -p
. With it, it is as simple as mkdir -p /tmp/1/2/3/
.
I ran into a problem recently where I need this exact sort of functionality but with JavaScript objects. I'm a fan of the Lodash API and they have something similar to it with the _.get function. It allows you to get path of an object using a string. Using that format as I model, I was able to come up with something fairly straight forward.
You call the function by passing in the target object, a path (string or array format), and the value you want to set at that path.