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 that is inherited.
One option to do so is the _.forOwn method in lodash that can be used as a way to loop over all the own properties of an object. 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 also.
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, and will not loop over anything in the prototype object. The lodash _.forIn method on the other hand will loop over both the own properties as well as the inherited properties.
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 is not that difficult in vanilla js. The hasOwnProperty Object prototype method can be used as a way to find out if the property of an object is the own property of that object rather than an inherited property for example.
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.