If I have this JS object literal:
var foo = {
Sussy: 4,
Billy: 5,
Jimmy: 2,
Sally: 1
};
How can I create a new, sorted object literal:
var bar = {
Sally: 1,
Jimmy: 2,
Sussy: 4,
Billy: 5
};
Re: How to sort a JS Object?
Answer: You can't. So instead, you need a more sophisticated data structure. You have many options:
I recommend solution 3 since it uses the JS mechanics to manage the ordering.
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 a.k.localeCompare(b.k);
});
// The third key and value:
woof[2].k; // the third key
woof[2].v; // the third value
Edited: updated code to fix typo. Thank you, @Martin Fido
Object properties are in no specific order (the order is implementation dependent) and you cannot sort the properties.
You have to keep an array of keys and sort it 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 values of the array and use them to access the corresponding property of the object.
Turns out object property order is predictable since ES2015. Which is amazing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.