How to iterate javascript object properties in the order they were written

Solution 1:

No. JavaScript Object properties have no inherent order. It is total luck what order a for...in loop operates.

If you want order you'll have to use an array instead:

var map= [[23, 'AA'], [12, 'BB']];
for (var i= 0; i<map.length; i++)
    document.write('Key '+map[i][0]+', value: '+map[i][1]);

Solution 2:

I think you'll find the only reliable way to do this would be to use an array rather than an associative array, eg:

var arr = [{key:23,val:"AA"},{key:12,val:"BB"}];
for(var i=0; i<arr.length; i++)
  document.write("Key: "+arr[i].key +" "+"Value: "+arr[i].val);