I believe this
is pointing to the wrong object but cannot figure out how to loop through an object
and on each iteration, call a method
from that nested object
.
Example:
var obj = {
one: {
id: 1,
name: 'one',
getName: function() {
return this.name();
}
},
two: {
id: 2,
name: 'two',
getName: function() {
return this.name();
}
}
};
for (var key in obj) {
console.log(key.getName());
}
This returns the error Object one has no method getName
. How can I access that nested method
?
You need to access the inner object using the key. Also, return name
as a property, not a method call
var obj = { one: { id: 1, name: 'one', getName: function() { return this.name; } }, two: { id: 2, name: 'two', getName: function() { return this.name; } } }; for (var key in obj) { console.log(obj[key].getName()); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.