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?

1
  • 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? Commented Aug 1, 2015 at 0:35

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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]();
  }
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.