If I have this JS object literal:
JavaScript
x
7
1
var foo = {
2
Sussy: 4,
3
Billy: 5,
4
Jimmy: 2,
5
Sally: 1
6
};
7
How can I create a new, sorted object literal:
JavaScript
1
7
1
var bar = {
2
Sally: 1,
3
Jimmy: 2,
4
Sussy: 4,
5
Billy: 5
6
};
7
Advertisement
Answer
Re: How to sort a JS Object?
Answer: You can’t. So instead, you need a more sophisticated data structure. You have many options:
- You can use a separate array to hold the order of the object’s keys. (This is what @Felix Kling’s answer demonstrates.) Good: fast retrieval via order or name. Bad: needs a second data structure that must be kept synched with the first.
- Instead of the Object simply holding properties and values, the properties could hold Objects which hold the values and a sort order. Good: 1 data structure. Fast lookup by property name. Bad: slow lookup by order (need to scan the structure). Slow sorting.
- Use an array, with elements consisting of Objects that hold the key and the value. Good: 1 data structure. Fast lookup by order. Fast sorting. Bad: slow lookup by property name (need to scan the structure).
I recommend solution 3 since it uses the JS mechanics to manage the ordering.
Examples:
JavaScript
1
25
25
1
// Object holds sort order: (Solution 2)
2
var foo = {
3
Suzy: {v: 4, order: 0},
4
Billy: {v: 5, order: 1},
5
Jimmy: {v: 2, order: 2},
6
Sally: {v: 1, order: 3}
7
};
8
9
// Array holds keys: (Solution 3)
10
var woof = [
11
{k: 'Suzy', v: 4},
12
{k: 'Billy', v: 5},
13
{k: 'Jimmy', v: 2},
14
{k: 'Sally', v: 1}
15
];
16
17
// Sort the woof array by the key names:
18
woof.sort(function(a, b) {
19
return a.k.localeCompare(b.k);
20
});
21
22
// The third key and value:
23
woof[2].k; // the third key
24
woof[2].v; // the third value
25
Edited: updated code to fix typo. Thank you, @Martin Fido