0

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?

jpishko
  • 1,070
  • 1
  • 10
  • 19
  • Theoretically, you could do `for(var f in myObject){myObject[f]();}`. But the return value will be lost. What do you want to do with the return values? – Sebastian Simon Aug 01 '15 at 00:35

3 Answers3

1

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.

reker-
  • 26
  • 3
0

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]();
  }
}
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
0

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?.

Community
  • 1
  • 1
Ethan Lynn
  • 1,009
  • 6
  • 13