0



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 :)

Navaneeth
  • 2,377
  • 1
  • 15
  • 36

2 Answers2

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
Juan Mendes
  • 80,964
  • 26
  • 138
  • 189
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]]);
});

Demo: http://jsfiddle.net/techfoobar/5kduC/

techfoobar
  • 61,046
  • 13
  • 104
  • 127