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

1
  • 1
    Iterating over an object doesn't return the properties in a predictable order; you could perhaps copy them to an array, and then sort/reverse that, though. Commented Nov 4, 2013 at 23:24

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

if it was an array, what would be the condition for the for-loop
Edited the answer, that's how you would use an array.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.