The lodash _.forown method
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.
However doins so is not so hard with plain old javaScript by itself also, so these methods are not the most compelling reasons to bother with lodash. With that being said I will be looking at some vanilla javaScript solutions for looping over the own properties of an object in addition to using lodash to do so.
1 - What to know
This is a post on the _.forOwn method in lodash, and related topics in javaScript. It is not a getting started post on lodash, or javaScript in general. I also will not be getting into prototype based inheritance in this post as well, as that is a matter for another post.
2 - A Basic example of _.forOwn
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 that is the difference between the _.forOwn, and _.forIn methods in lodash. If you are just using plain javaScript though no problem there is the for in loop, and the has own property object prototype method that can be used.
3 - Using a for in loop
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.
4 - Conclusion
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.