Loop through properties in JavaScript object with Lodash

后端 未结 7 1951
闹比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: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.

提交回复
热议问题