-2

I have an object in javascript

var o = [
  {city: 'armenia', population: 300000}, 
  {city: 'russia', population: 1200000}
];  

I need to loop through it; please help

Paul Roub
  • 36,322
  • 27
  • 84
  • 93

2 Answers2

0

This question been answered before. Needless to say loop thru the array using the length property and loop thru the object using a foreach loop. for each...in

for (var i = 0; i < o.length; i++) {
      var obj = o[i];

      for (var key in obj) {
           // key
           console.log(key);

           // value
           console.log(obj[key]);
      }
 }
Jay Harris
  • 4,201
  • 17
  • 21
0
o.forEach(function (c) {
  console.log(c.city, c.population); // "armenia" 300000, "russia" 1200000
})

or

for(var i = 0; i < o.length; i++) {
  console.log(o[i].city, o[i].population);
}

DEMO

brbcoding
  • 13,378
  • 2
  • 37
  • 51