The lodash forIn method
1 - Lodash for in method, and what to know before hand
1.1 - Basic example of _.forIn
The _.forIn lodash method will loop over all own, and inherited properties of an object. In other words the key value pairs that are specific to the object, as well as anything that is part of the objects prototype. Other options for loping over the contents of an object might just loop over what is an actual Constructor object instance property, rather than any additional properties that might be present in the prototype of the Constructor.
2 - Vanilla js alternatives to _.forin
2.1 - Starting out with just a simple for in loop example
Just a plain old for in loop seems to work just fine to loop over own properties of an object as well as what is in the prototype object as well. There is the fact that a for in loop is a kind of loop rather than a function that will take a function as an argument, but this is a problem that is very easily solved by just making my own kind of function that is like the lodash for in loop.
2.2 - Using Object.keys, Array concat, and Array for each
Another way would be to create an array of key names, and loop over that array of key names by one means of doing so or another. Using Object.keys will give me all the enumerable properties of an object, but not it’s prototype, unless I give the prototype object itself to the object keys method. So I could use Object.keys twice, and then use an array method like array concat to create a single array of keys that way. Then it is just a matter of looping over these key names and then use the keys to get references to the values inside the body of the loop.
2.3 - Making a custom for in method
3 - Conclusion
So _.forIn is useful for just quickly looping over both the own properties, as well as inherited properties of an Object. The only types of properties that it will not loop over are non enumerable properties. However that can be done in vanilla js with the help of Object.getOwnPropertyNames. I would get into that in detail as well but that is a matter for another post. If you enjoyed this post you might want to also check out mu posts on _.forOwn which is just like _.forIn only it loops of the own properties of an object. There are also a whole lot of other methods in lodash that have to do with looping over the contents of a collection in one form or another though each of which are worth looking into at least once. So if you are looking for more to read up on with lodash there is checking out my main post on lodash, or reading one of my many other posts on various lodash methods, and other relevant topics.