Friday, 23 September 2016

Loop through properties in JavaScript object with Lodash



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



Yes you can and lodash is not needed... i.e.



for (var key in myObject.options) {
// check also if property is not inherited from prototype
if (myObject.options.hasOwnProperty(key)) {

var value = myObject.options[key];
}
}


Edit: the accepted answer (_.forOwn()) should be https://stackoverflow.com/a/21311045/528262


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...