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
Larry k
source share