Hedge
Hedge

Reputation: 16748

Iterate and call methods inside array-like objects

I've got this object-structure and would like to iterate over all direct child objects of obj and call their myMethod method. While for...in iterates over them correctly I always get this error o.myMethod is not a function

Here is a JSFiddle

obj = {
    test1: {
        "name": "test1string",
        "myMethod": function(){
            console.log("test 1 method called")
        }
    },
    test2: {
        "name": "test2string",
         "myMethod": function(){
            console.log("test 2 method called")
        }
    }
};

for (var o in obj) {
    console.log(o.name());
    o.myMethod();
}

How can I achieve the wanted behaviour?

Upvotes: 2

Views: 42

Answers (3)

Akshendra Pratap
Akshendra Pratap

Reputation: 2040

Use it like this obj[o].name. Here's the updated fiddle

Upvotes: 1

VisioN
VisioN

Reputation: 145398

This happens because o in your for loop corresponds to keys and not to values.

To get the value use square-bracket notation: obj[o].myMethod();.

Upvotes: 4

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39370

obj[o].myMethod(). for .. in gives you names of members, not the values.

Upvotes: 2

Related Questions