Thursday 23 February 2017

javascript - How to loop thru this kind of array and get the label or name of each element





I have this array: I don't know what kind of array this is.



var catz ={
cafe:{class:'orange',color:'E6674A',font:'000'},
bar:{class:'orange',color:'E6674A',font:'000'},
restaurant:{class:'green',color:'a8e52f',font:'000'}

};


and I'm trying to alert the category: Ex. it should alert: cafe, then bar, and then restaurant.



for (var j = 0;j < 3;j++){
alert (catz[j]);
}



then I'd like to also get the color



it works with this array, but I'm using the other array.



var catz = ["cafe", "bar", "restaurant"];


Thanks


Answer



try this:




var catz ={
cafe:{class:'orange',color:'E6674A',font:'000'},
bar:{class:'orange',color:'E6674A',font:'000'},
restaurant:{class:'green',color:'a8e52f',font:'000'}
};

for(var key in catz){
alert(key + " : " + catz[key].color);
}



this will alert cafe : E6674A, and so on...



http://jsfiddle.net/ashishanexpert/qVp5u/


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...