Loop through properties in JavaScript object with Lodash

后端 未结 7 1941
闹比i
闹比i 2021-02-01 00:01

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:         


        
相关标签:
7条回答
  • 2021-02-01 00:25

    Lets take below object as example

    let obj = { property1: 'value 1', property2: 'value 2'};
    

    First fetch all the key in the obj

    let keys = Object.keys(obj) //it will return array of keys
    

    and then loop through it

    keys.forEach(key => //your way)
    

    just putting all together

    Object.keys(obj).forEach(key=>{/*code here*/})
    
    0 讨论(0)
  • 2021-02-01 00:38

    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.

    0 讨论(0)
  • 2021-02-01 00:39

    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

    0 讨论(0)
  • 2021-02-01 00:40

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

    var exists = _.has(myObject, propertyNameToCheck);
    
    0 讨论(0)
  • 2021-02-01 00:43

    It would be helpful to understand why you need to do this with lodash. If you just want to check if a key exists in an object, you don't need lodash.

    myObject.options.hasOwnProperty('property');
    

    If your looking to see if a value exists, you can use _.invert

    _.invert(myObject.options)[value]
    
    0 讨论(0)
  • 2021-02-01 00:44

    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.

    0 讨论(0)
提交回复
热议问题