//dict -> a js object
var dict = {"x" : 1,
"y" : 6,
"z" : 9,
"a" : 5,
"b" : 7,
"c" : 11,
"d" : 17,
"t" : 3};
//Use the 'keys' function from the Object class to get the keys of your dictionary
//'keys' will be an array containing ["x", "y", "z"...]
var keys = Object.keys(dict);
//Get the number of keys - easy using the array 'length' property
var i, len = keys.length;
//Sort the keys. We can use the sort() method because 'keys' is an array
keys.sort();
//This array will hold your key/value pairs in an ordered way : it will be an array of objects
var sortedDict = [];
//Now let's go throught your keys in the sorted order
for (i = 0; i < len; i++)
{
//get the current key
k = keys[i];
//show you the key and the value (retrieved by accessing dict with current key)
alert(k + ':' + dict[k]);
//Using the array 'push' method, we add an object at the end of the result array
//It will hold the key/value pair
sortedDict.push({'key': k, 'value':dict[k]});
}
//Result
console.log(sortedDict);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!