First thing is first lets get the hello world style example of this get method out of the way. With that said there is starting out with some kind of object that has many additional objects nested in it. When it comes to this kind of example the lodash get method can be used to get any object or primitive value within this kind of object of objects. First I pass the source object I want to get something in as the first argument, then a string that is a path to the value that I want, then an optional default value that will be what is returned in the event that that value is not there.
The _.get method works by passing the object I want to get a value from first, and then a path in string form as the second argument, following by an optional default value in the event that there is nothing at the given path.
So when it comes to just grabbing at values, and I do not need to do so with a string form I can always just use the dot operator, or I can use square brackets to get a value if I can break down the path into more than one string.
In most cases I can do just fine with one of these just fine, but if for some reason I really do want to get an object value by a path in string from then I Might need to find a copy an past solution on stack overflow, or make one.
So now there is the question of making ones own lodash get method that works more or less the same way. Most of the time making a stand alone method for a lodash method is not so hard, and the lodash get method is not really an exception to this. I quickly put together this in a flash, for the most part it seems to work in the same manner, but it is not battle tested.
Although it might not take to long to make my own solution for a lot of these methods in lodash if there is not a native method to use, it is still way longer than just using _.get if lodash is part of the stack.
Quickly looking over some chatter on stack overflow, and comments at the issues section at the lodash github repository it seems like one of the biggest issues to look out for is that the default value will only return if the value turns out to be undefined. If you expect the default value to return if the path returns a value like null, or false that is one reason why you might want to make your own solution for _.get. It would not be to hard to add a forth argument to the vanilla js alternative that could be an array of values to return the default for.
If you enjoyed this post you might want to check out one of my many other posts on lodash.