Sort JavaScript object by key
I need to sort JavaScript objects by key.
Hence the following:
{ 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }
Would become:
{ 'a' : 'dsfdsfsdf', 'b' : 'asdsad', 'c' : 'masdas' }
The other answers to this question are outdated, never matched implementation reality, and have officially become incorrect now that the ES6/ES2015 spec has been published.
See the section on property iteration order in Exploring ES6 by Axel Rauschmayer:
All methods that iterate over property keys do so in the same order:
So yes, JavaScript objects are in fact ordered, and the order of their keys/properties can be changed.
Here's how you can sort an object by its keys/properties, alphabetically:
const unordered = {
'b': 'foo',
'c': 'bar',
'a': 'baz'
};
console.log(JSON.stringify(unordered));
// → '{"b":"foo","c":"bar","a":"baz"}'
const ordered = {};
Object.keys(unordered).sort().forEach(function(key) {
ordered[key] = unordered[key];
});
console.log(JSON.stringify(ordered));
// → '{"a":"baz","b":"foo","c":"bar"}'
Use var
instead of const
for compatibility with ES5 engines.
JavaScript objects1 are not ordered. It is meaningless to try to "sort" them. If you want to iterate over an object's properties, you can sort the keys and then retrieve the associated values:
var myObj = {
'b': 'asdsadfd',
'c': 'masdasaf',
'a': 'dsfdsfsdf'
},
keys = [],
k, i, len;
for (k in myObj) {
if (myObj.hasOwnProperty(k)) {
keys.push(k);
}
}
keys.sort();
len = keys.length;
for (i = 0; i < len; i++) {
k = keys[i];
alert(k + ':' + myObj[k]);
}
A lot of people have mention that "objects cannot be sorted" , but after that they are giving you a solution which works. Paradox, isn't it?
No one mention why those solutions are working. They are, because in most of the browser's implementations values in objects are stored in the order in which they were added. That's why if you create new object from sorted list of keys it's returning an expected result.
And I think that we could add one more solution – ES5 functional way:
function sortObject(obj) {
return Object.keys(obj).sort().reduce(function (result, key) {
result[key] = obj[key];
return result;
}, {});
}
ES2015 version of above (formatted to "one-liner"):
function sortObject(o) {
return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}
Short explanation of above examples (as asked in comments):
Object.keys
is giving us a list of keys in provided object ( obj
or o
), then we're sorting those using default sorting algorithm, next .reduce
is used to convert that array back into an object, but this time with all of the keys sorted.
下一篇: 按键排序JavaScript对象