-2

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

j08691
  • 204,283
  • 31
  • 260
  • 272
Sebastian
  • 475
  • 2
  • 8
  • 19

3 Answers3

2

You can iterate over properties of an object using a for in loop.

for (var key in catz) {
    if (catz.hasOwnProperty(key))
        console.log(key, catz[key]);
}

Console output:

cafe Object {class: "orange", color: "E6674A", font: "000"}
bar Object {class: "orange", color: "E6674A", font: "000"}
restaurant Object {class: "green", color: "a8e52f", font: "000"}
Nicolae Olariu
  • 2,487
  • 2
  • 18
  • 30
2

walk through the object and retrieve the keys

for (category in catz) {
   if (catz.hasOwnProperty(category)) {
      console.log(category)
   }
}

Note: in your specific example the if statement could not be really necessary (see this answer - comment included - for further information)

Community
  • 1
  • 1
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
2

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/

Ashish Kumar
  • 2,991
  • 3
  • 18
  • 27