4

I'm trying to find the best way to iterate over all of the values on an enum defined in Google Closure. Let's say I have the following enum defined:

/**
 * @enum {number}
 */
sample.namespace.Fruit = {
  Orange: 0,
  Apple: 1,
  Banana: 2
};

Right now, the best way I've seen to do this would be something like this:

for (var key in sample.namespace.Fruit) {
    var fruit = /** @type {sample.namespace.Fruit} */ (sample.namespace.Fruit[key]);
    // Make a smoothie or something.
}

I consider that painful to read. I'm listing a namespace three times just to get the compiler to come along for the ride. Is there another iteration technique that I should be using instead? Is this the best way to accomplish this form of iteration?

Technetium
  • 5,902
  • 2
  • 43
  • 54

2 Answers2

5

You can use goog.object.forEach to avoid namespace repetition.

goog.object.forEach(sample.namespace.Fruit,
                    function(value, key, allValues) {
                      // Make some delicious fruit jellies or something.
                    });

As a side note, in most cases you want to avoid using string keys for @enums so the compiler can rename those.

Derek Slager
  • 13,619
  • 3
  • 34
  • 34
3

You can use a for loop to iterate over your objects..

var obj = sample.namespace.Fruit;

for(var key in obj) {
    console.log("Fruit :: " + key + " -- " + obj[key])
}

Check Fiddle

Sushanth --
  • 55,259
  • 9
  • 66
  • 105