0

Possible Duplicate:
Sorting a JSON object in Javascript

I have an object with key and value pair.

var obj = {
   'key1':'z',
   'key2':'u',
   'key3':'a',
   'key4':'c',
   'key5':'b',
   'key6':'e'
}

I have to sort my values in alphabetical order like this, but look at the keys they have also changed accordingly.

    var obj = {
           'key3':'a',
           'key5':'b',
           'key4':'c',
           'key6':'e',
           'key2':'u',
           'key1':'z'
   }
Community
  • 1
  • 1
theJava
  • 14,620
  • 45
  • 131
  • 172

1 Answers1

1

You cannot sort object properties. Object properties behave like a hash map where the iteration order of properties may not reflect the order in your source code or JSON payload.

You should look into storing your data as an Array:

var arr = [{
   key: "key1", value: "z"
}, {
   key: "key2", value: "u"
}, {
   ...
}];

var sorted = arr.sort(function (a, b) {
    return a.key === b.key ? 0
        : a.key < b.key ? -1 : 1;
});
Ates Goral
  • 137,716
  • 26
  • 137
  • 190