0
for (var key in validation_messages) {
 var obj = validation_messages[key];
 for (var prop in obj) {
  if(obj.hasOwnProperty(prop)){
  alert(prop + " = " + obj[prop]);
  }
 }
}

This is the for loop that i have but i'm getting the response in ascending order. But i need it in descending order. Can some one help me.

Thanks

user2954417
  • 17
  • 2
  • 8

2 Answers2

2

Javascript does not guarantee a specific object property order, see this: Does JavaScript Guarantee Object Property Order?

If you need a specific order, you should use an array.

If you had them in an array, the code would look like this(fiddle:http://jsfiddle.net/DH3VQ/1/) :

var props = [
    { key:"p1", value:"a"},   
    { key:"p2", value:"b"},   
    { key:"p3", value:"c"},   
];

for (var i = 0; i< props.length; i++){
    alert(props[i].key + " = " + props[i].value);
}   

Or you could do something fancier:

   props.forEach(function(prop){alert(prop.key + " = " + prop.value)});

But the standard for is probably more portable.

Community
  • 1
  • 1
pax162
  • 4,675
  • 2
  • 19
  • 27
1

Like this:

Object.keys(validation_messages)
      .sort(function(a,b) {
           return b.localeCompare(a);
      })
      .forEach(function(key) {
           var val = validation_messages[key];

           console.log(key, val);
      });

Object.keys gets the enumerable properties of an object into an Array. Then the .sort() will sort them in descending order, and the .forEach() will iterate the sorted set of keys.

So then for each key, you can grab the value from the object, and use it.

Blue Skies
  • 2,847
  • 14
  • 19