154

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?

APerson
  • 8,140
  • 8
  • 35
  • 49
user3111277
  • 2,237
  • 3
  • 17
  • 19

9 Answers9

660

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.

djechlin
  • 59,258
  • 35
  • 162
  • 290
45

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

stecb
  • 14,478
  • 2
  • 50
  • 68
  • 6
    + I know they want lodash funct-style, mine was just a way to let the OP understand u can loop an obj w/out depending on a library (in case he just wants that functionality w/o including lodash) – stecb Jan 23 '14 at 14:36
  • 40
    In which case, providing both answers would have been nice. – flq Jul 31 '15 at 20:16
  • 4
    using `lodash` and not this is justified only by not needing the annoying `hasOwnProperty` check – Mugen Nov 09 '19 at 16:37
18

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

var exists = _.has(myObject, propertyNameToCheck);
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
9

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.

Kevinleary.net
  • 8,851
  • 3
  • 54
  • 46
4

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*/})
Akki geek
  • 71
  • 6
1

In ES6, it is also possible to iterate over the values of an object using the for..of loop. This doesn't work right out of the box for JavaScript objects, however, as you must define an @@iterator property on the object. This works as follows:

  • The for..of loop asks the "object to be iterated over" (let's call it obj1 for an iterator object. The loop iterates over obj1 by successively calling the next() method on the provided iterator object and using the returned value as the value for each iteration of the loop.
  • The iterator object is obtained by invoking the function defined in the @@iterator property, or Symbol.iterator property, of obj1. This is the function you must define yourself, and it should return an iterator object

Here is an example:

const obj1 = {
  a: 5,
  b: "hello",
  [Symbol.iterator]: function() {
    const thisObj = this;
    let index = 0;
    return {
      next() {
        let keys = Object.keys(thisObj);
        return {
          value: thisObj[keys[index++]],
          done: (index > keys.length)
        };
      }
    };
  }
};

Now we can use the for..of loop:

for (val of obj1) {
  console.log(val);
}    // 5 hello
evianpring
  • 3,316
  • 1
  • 25
  • 54
0

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]
Barry G
  • 221
  • 4
  • 14
0

If you just want to loop through to map property values then use _.mapValues

danday74
  • 52,471
  • 49
  • 232
  • 283
0

If you are checking, if the property exists in the object as stated in the question asked, you can use lodash libray _.has method

_.has(object, path)

Let me give you an example, how to use it.

consider an object

    const user = {
    name : "prabhat",
    age: 27,
    height: "5.7"
   }

if you want to check, if name property exist in the object,you can use _.has method as follows

_.has(user, 'name') //true
_.has(user, 'address') //false

you will get a boolean true/false in return.

prabhat kumar jena
  • 12,819
  • 1
  • 10
  • 10