jpishko
jpishko

Reputation: 1070

How to iterate through functions defined in a javascript object

I have an object that defines a bunch of functions like this:

myObject = {
  "item 1": function() {
    return "I'm item 1";
  },
  "item 2": function() {
    return "I'm item 2";
  }
};

I want to write a function that calls all of the functions defined in this object without having to know the names of the functions or the number of functions. Is this possible?

Upvotes: 0

Views: 70

Answers (3)

Ethan Lynn
Ethan Lynn

Reputation: 1009

You could either use Object.keys or a for-in loop depending on your needs.

Object.keys(obj); // ==> ["item-1", "item-2"]
Object.keys(obj).forEach(function (key) {
    var fn = obj[key];
    fn();
});

// or with a for-in loop

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        obj[key]();
    }
}

Using Object.keys is arguably a bit more clear, but the for-in loop has better browser compatibility and possibly performance. For a more general comparison of object enumeration in JavaScript, refer to this question How do I enumerate the properties of a JavaScript object?.

Upvotes: 0

reker-
reker-

Reputation: 26

In ECMAScript >=5.1 you can use the for .. in construct.

obj = {
    test : function() {
        console.log("test called");
    }
};

for(idx in obj) {
    obj[idx]();
}

You may want to check that the property is actually a function.

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32511

You can do this by first using a for-in loop to go through each of the objects properties. Then, after checking if the value is a function, you can call it.

for (var key in obj) {
  if (typeof obj[key] === 'function') {
    obj[key]();
  }
}

Upvotes: 0

Related Questions