1

How to iterate over the following object so that the output listed below to be generated?

var obj = { a: "1", b: "2", c: "3" };

The expected output:

index: 0 value1: a value2: 1  
index: 1 value1: b value2: 2  
index: 2 value1: c value2: 3
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
frogatto
  • 28,539
  • 11
  • 83
  • 129

3 Answers3

4

You can use for .. in to iterate over the object's keys instead and use a separate counter for the index:

var index = 0;
for (var key in obj) {
    console.log("index: " + index + " value1: " + key + " value2: " + obj[key]);
    ++index;
}

If your environment is sane, this should just work; if not, you would have to add the mandatory hasOwnProperty() check.

Iterating over the object keys using Object.keys() is possible in modern browsers, but if memory is tight the above method would be preferable.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
2

In modern browsers you can loop like this:

Object.keys(obj).forEach(function(key, i){
  console.log('index: '+ i, 'key: '+ key, 'value: '+ obj[key]);
});
elclanrs
  • 92,861
  • 21
  • 134
  • 171
1

It is an object and you are trying to iterate it as an array. Use for-in construct.

var obj = { a: "1", b: "2", c: "3" };

for(var opt in obj) {
    console.log(opt + ": " + obj[opt]);
}
Abhitalks
  • 27,721
  • 5
  • 58
  • 81