EN
JavaScript - get object properties sorted by key
3 points
In this article, we would like to show you how to get object properties sorted by key in JavaScript.
Note:
Object properties are ordered since ES6.
The main concept of this solution is to use:
keys()
method which returns an array of given object property names,sort()
method to sort the array,reduce()
method to create a new object from the array with sorted properties.
Runnable example:
xxxxxxxxxx
1
const object = {
2
'b': 'bb',
3
'c': 'cc',
4
'a': 'aa'
5
};
6
7
const sortedObject = Object.keys(object)
8
.sort()
9
.reduce((result, key) => (result[key] = object[key], result),{});
10
11
console.log(JSON.stringify(object)); // {"b":"bb", "c":"cc", "a":"aa"}
12
console.log(JSON.stringify(sortedObject)); // {"a":"aa", "b":"bb", "c":"cc"}
Note:
The default sort order is ascending but elements converted into strings are compared by their sequences of UTF-16 code units values.