Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through properties in JavaScript object with Lodash

People also ask

Can you loop through properties of an object JavaScript?

Object. entries() is the recommended method for iterating over an object's properties in JavaScript. Since the method returns a multidimensional array, we can greatly simplify our code by using the array destructuring syntax to retrieve each property into a separate variable.

Which JavaScript loop loops through the properties of an object?

A for...in loop only iterates over enumerable, non-Symbol properties. Objects created from built–in constructors like Array and Object have inherited non–enumerable properties from Array. prototype and Object.

What is a for in loop for properties?

Description. In JavaScript, the for-in loop is a basic control statement that allows you to loop through the properties of an object. The statements of code found within the loop body will be executed once for each property of the object.

What is Lodash used for in JavaScript?

Lodash is a popular javascript based library which provides 200+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on.


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.


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


For your stated desire to "check if a property exists" you can directly use Lo-Dash's has.

var exists = _.has(myObject, propertyNameToCheck);

You can definitely do this with vanilla JS like stecb has shown, but I think each is the best answer to the core question concerning how to do it with lodash.

_.each( myObject.options, ( val, key ) => { 
    console.log( key, val ); 
} );

Like JohnnyHK mentioned, there is also the has method which would be helpful for the use case, but from what is originally stated set may be more useful. Let's say you wanted to add something to this object dynamically as you've mentioned:

let dynamicKey = 'someCrazyProperty';
let dynamicValue = 'someCrazyValue';

_.set( myObject.options, dynamicKey, dynamicValue );

That's how I'd do it, based on the original description.