I have to retrieve the keys in the reverse order from javascript object.
$.each()
retrive in the declared order
for example,
var a={'b':1,'c':2};
output must be {'c':2,'b':1}
thanx :)
Asked
Active
Viewed 1,702 times
0

Navaneeth
- 2,555
- 1
- 18
- 38
2 Answers
3
JavaScript objects have no guaranteed order of keys when iterating. Does JavaScript Guarantee Object Property Order?
If you must rely on order, you have to use an array. Don't be fooled into thinking you can rely on this unspecified behavior. People have been asking chrome to make iteration reliable but they are not going to. http://code.google.com/p/chromium/issues/detail?id=883 is marked as won't fix, because JavaScript never guaranteed it.

Community
- 1
- 1

Ruan Mendes
- 90,375
- 31
- 153
- 217
-
If it doesnot follow an order, then why $.each() gives key,value pair in the order we declare?? – Navaneeth Sep 13 '12 at 08:27
1
Use:
$(_array).reverse().each(function(i) {
// ...
});
For objects, you can do:
var a = {a: 2, b: 1};
console.log('Declared order');
$.each(a, function(i) {
console.log(i+': '+a[i]);
});
console.log('Reverse order');
var keys = [];
for(var k in a) keys.unshift(k);
$.each(keys, function(i) {
console.log(keys[i]+': '+a[keys[i]]);
});

techfoobar
- 65,616
- 14
- 114
- 135
-
-
see my edit. but do note that there is no guarantee regarding the order (though in most cases, you will get it in the order you declared) – techfoobar Sep 13 '12 at 08:34
-
The cases where you will get in trouble (as of today, will certainly change): if property name starts with an integer or if you remove and add the same property again. – Ruan Mendes Sep 13 '12 at 08:39
-
Yes, its safer not to be depending on the order of properties while iterating. – techfoobar Sep 13 '12 at 08:41