2

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?

3 Answers 3

4

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();.

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

Comments

2

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

Comments

1

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

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.