Sorting a Javascript Object

I came across strange problem recently, i have an JavaScript Object. since this object represents a map structure we cannot directly sort the data of the map based on key. After goggling found a simple solution and this will demonstrate how we can sort the map like structure by key in JavaScript.

To start with we have an JavaScriptobject having data in key-value format as shown below

var data = {};
data["ASDFG"] = 123;
data["GKLK"] = 234;
data["AQWED"] = 567;
data["AAACC"] = 987;

Now i want to sort this data by key so that the end result would be

"AAACC":987
"AQWED":567
"ASDFG":123
"GKLK":234

Below is the final code that would help us to sort the object by key/value structure

  var data = {};
  data["ASDFG"] = 123;
  data["GKLK"] = 234;
  data["AQWED"] = 567;
  data["AAACC"] = 987;
 
  var objectKeys = [];    //This would hold the sorted key
  var sortedObject = {};  //This would hold the final object sorted on keys
 
  //Loop through the object and extract all the keys
  for(var key in data)
  {
      if (data.hasOwnProperty(key))    //This will tell u whether the key is present in the object as an property
      {
         objectKeys.push(key);
      }
  }
 
  //Now sort the objectKeys, this would return an array with sorted keys
  objectKeys.sort();
 
  //Loop through the sorted array and populate the new object with the data
  for(var i=0;i<objectkeys .length;i++)
  {
      sortedObject[objectKeys[i]] = data[objectKeys[i]];
  }
 
  //Finally alert the object and check the content
  alert(JSON.stringify(sortedObject));


Related Articles:

About Hitesh Agrawal

Wait... checking
Tagged . Bookmark the permalink.

One Response to Sorting a Javascript Object

  1. Thanks for sharing.. I see myself using this at many occasions in the future

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>