How to sort JS object literal?

If I have this JS object literal:

var foo = { Sussy: 4, Billy: 5, Jimmy: 2, Sally: 1 }; 

How to create a new, sorted object literal:

 var bar = { Sally: 1, Jimmy: 2, Sussy: 4, Billy: 5 }; 
+8
javascript sorting object-literal
source share
2 answers

Re: How to sort a JS object?

Answer: You cannot. So instead, you need a more complex data structure. You have many options:

  • You can use a separate array to store the order of the keys of objects. (This is what @Felix Kling's answer demonstrates.) Good: quick search in order or name. Bad: a second data structure is required, which must be synchronized with the first.
  • Instead of an object that simply stores properties and values, properties can contain objects that store values ​​and sort order. Good: 1 data structure. Quick search by property name. Bad: Slow order search (structure required to scan). Slow sorting.
  • Use an array with elements consisting of objects containing a key and a value. Good: 1 data structure. Quick search on order. Quick sorting. Bad: Slow search by property name (structure needs to be scanned).

I recommend solution 3, as it uses JS mechanics to control order.

Examples:

 // Object holds sort order: (Solution 2) var foo = { Suzy: {v: 4, order: 0}, Billy: {v: 5, order: 1}, Jimmy: {v: 2, order: 2}, Sally: {v: 1, order: 3} }; // Array holds keys: (Solution 3) var woof = [ {k: 'Suzy', v: 4}, {k: 'Billy', v: 5}, {k: 'Jimmy', v: 2}, {k: 'Sally', v: 1} ]; // Sort the woof array by the key names: woof.sort(function(a, b) { return aklocaleCompare(bk); }); // The third key and value: woof[2].k; // the third key woof[2].v; // the third value 

Edited: Updated code to correct typos. Thanks @Martin Fido

+9
source share

The properties of an object do not have a specific order (the order depends on the implementation), and you cannot sort the properties.

You must store an array of keys and sort them accordingly, for example:

 var keys = []; for(var key in obj) { if(obj.hasOwnProperty(key)) { keys.push(key); } } keys.sort(function(a, b) { return obj[a] - obj[b]; }); 

Now you can iterate over the array values ​​and use them to access the corresponding property of the object.

+6
source share

All Articles