Loop through properties in JavaScript object with Lodash

user3111277 picture user3111277 · Jan 23, 2014 · Viewed 148.4k times · Source

Is it possible to loop through the properties in a JavaScript object? For instance, I have a JavaScript object defined as this:

myObject.options = {
  property1: 'value 1',
  property2: 'value 2'
};

Properties will get dynamically added to this object. Is there a way for me to just loop through and do a check if a property exists? If so, how?

Answer

djechlin picture djechlin · Jan 23, 2014

Use _.forOwn().

_.forOwn(obj, function(value, key) { } );

https://lodash.com/docs#forOwn

Note that forOwn checks hasOwnProperty, as you usually need to do when looping over an object's properties. forIn does not do this check.