Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

I identified a bug in my code which I hope to solve with minimal refactoring effort. This bug occurs in Chrome and Opera browsers. Problem:

var obj = {23:"AA",12:"BB"};
//iterating through obj's properties
for(i in obj)
  document.write("Key: "+i +" "+"Value: "+obj[i]);

Output in FF,IE Key: 23 Value: AA Key: 12 Value: BB

Output in Opera and Chrome (Wrong)
Key: 12 Value BB
Key: 23 Value AA

I attempted to make an inverse ordered object like this

var obj1={"AA":23,"BB":12};
for(i in obj1)
  document.write("Key: "+obj[i] +" "+"Value: "+i);

However the output is the same. Is there a way to get for all browser the same behaviour with small changes?

like image 527
Eugeniu Torica Avatar asked Apr 15 '10 16:04

Eugeniu Torica


People also ask

How can you iterate over the properties of a JavaScript object?

If you would like to iterate directly over the values of the keys of an object, you can define an iterator , just like JavaScipts's default iterators for strings, arrays, typed arrays, Map and Set. JS will attempt to iterate via the default iterator property, which must be defined as Symbol. iterator .

Are JavaScript object properties ordered?

To illustrate that JavaScript object keys are not ordered, let's compare them to an array: a simple list of items in a specific order. JavaScript arrays have a defined order from index 0 to the last item in the list, and items added to the array using . push() stay in the order they are added in.

Which method will you use to iterate the properties of an object?

The for...in statement iterates over all enumerable string properties of an object (ignoring properties keyed by symbols), including inherited enumerable properties.

Can we iterate object JavaScript?

Here's a very common task: iterating over an object properties, in JavaScript. If you have an object, you can't just iterate it using map() , forEach() or a for..of loop.


2 Answers

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]);
like image 93
bobince Avatar answered Oct 12 '22 18:10

bobince


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);
like image 25
Graza Avatar answered Oct 12 '22 17:10

Graza