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'
   }
2
  • 1
    Not all browsers let you specify the order of keys of objects. Commented Feb 7, 2012 at 8:28
  • 1
    See here (possible duplicate) Commented Feb 7, 2012 at 8:32

1 Answer 1

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;
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.