Looping over all keys in an object is something that comes up a whole lot when working on a javScript project. Sometimes it would be nice to have a method that will only loop over key value pares that are actually part of the object rather than it’s prototype. For this there is the _.forOwn method in lodash that makes this very easy. There is also of course the _.forIn method as well that will loop over the own properties of an object as well as what is in the prototype object as well.
For a basic example of _.forOwn I put together a quick example that involves a custom made constructor method, and a prototype for that method. The _.forOwn method will loop over just the own properties of the object.
So _.forOwn is one of those methods in lodash where I am scratching my head wondering why I should bother with lodash, because doing things like this are not that difficult in vanilla js.
The for in loop will loop over the own properties of an object as well inherited properties, so the hasOwnProperty method has to be used as a way to filter those out, and just have the own properties of the object.
One nice things about the _.forOwn method is that it may be a bit more concise compared to writing out a for in loop. That is something of value because I find that making code more concise may help to improve readability, other then that I cant say it is to big of a deal to do this the vanilla js way. If you enjoyed this post be sure to check out my other posts on lodash, and if you have any questions or concerns feel free to drop a line in the comments.