Reputation: 16748
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
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
Reputation: 39370
obj[o].myMethod()
. for .. in
gives you names of members, not the values.
Upvotes: 2