I am trying to access a property (name) on an object that is in fact located inside another object. I initialized the object in a file:
var icons = {
"facebook": {name: 'facebook', icon_url: 'img/logos/facebook.png'}
};
And then tried to check the object with this code:
var icon_current_class;
for(var icon in icons){
console.dir(icon);
//outputs an object named facebook but says it has no properties
if( $(this).hasClass( icon.name ) ){
icon_current_class = icon.name;
}else{
alert("Something went wrong. Please contact the mods.");
}
}
And of course, the alert("Something went wrong") goes off everytime I run this. I have tried for a long time to find a solution, but to no avail. Can anyone please help?
I am trying to access a property (name) on an object that is in fact located inside another object. I initialized the object in a file:
var icons = {
"facebook": {name: 'facebook', icon_url: 'img/logos/facebook.png'}
};
And then tried to check the object with this code:
var icon_current_class;
for(var icon in icons){
console.dir(icon);
//outputs an object named facebook but says it has no properties
if( $(this).hasClass( icon.name ) ){
icon_current_class = icon.name;
}else{
alert("Something went wrong. Please contact the mods.");
}
}
And of course, the alert("Something went wrong") goes off everytime I run this. I have tried for a long time to find a solution, but to no avail. Can anyone please help?
Share Improve this question asked Oct 20, 2013 at 22:02 Marcos PereiraMarcos Pereira 1,17115 silver badges26 bronze badges 2-
3
JavaScript's
in
is always for keys rather than values. – Jonathan Lonowski Commented Oct 20, 2013 at 22:05 -
2
You should just read the
for...in
documentation: developer.mozilla/en-US/docs/Web/JavaScript/Reference/…. – Felix Kling Commented Oct 20, 2013 at 22:27
2 Answers
Reset to default 6for(var x in y)
x
is the key of the object, you need to use y[x]
to return the value:
for(var icon_name in icons){
var icon = icons[icon_name];
.....code....
}
for(var icon in icons)
In the for loop, icon
you're assigned there isn't an object, it's the index/key of each item.
for (var i in icons){
console.dir(icons[i]);
...