Borislav Hadzhiev
Tue Feb 22 2022·2 min read
Photo by Ant Rozetsky
To sort the keys of an object:
Object.keys()
method to get an array of the object's keys.sort()
method on the array.reduce()
method to get an object with sorted keys.const obj = {z: 'three', a: 'one', b: 'two'}; const sorted = Object.keys(obj) .sort() .reduce((accumulator, key) => { accumulator[key] = obj[key]; return accumulator; }, {}); console.log(sorted); // 👉️ {a: 'one', b: 'two', z: 'three'}
We used the Object.keys method to get an array of the object's keys.
const obj = {z: 'three', a: 'one', b: 'two'}; // 👇️ ['z', 'a', 'b'] console.log(Object.keys(obj));
The next step is to use the Array.sort() method to sort the array of keys.
const obj = {z: 'three', a: 'one', b: 'two'}; // 👇️ ['a', 'b', 'z'] console.log(Object.keys(obj).sort());
At this point we have a sorted array containing the object's keys.
The last thing we have to do is use the Array.reduce method to iterate over the sorted array of keys and assign each key-value pair to an object.
const obj = {z: 'three', a: 'one', b: 'two'}; // 👇️ ['a', 'b', 'z'] console.log(Object.keys(obj).sort()); const sorted = Object.keys(obj) .sort() .reduce((accumulator, key) => { accumulator[key] = obj[key]; return accumulator; }, {}); console.log(sorted); // 👉️ {a: 'one', b: 'two', z: 'three'}
The function we passed to the reduce()
method gets called with each element
(key) in the array.
We've provided an empty object as the initial value for the accumulator
variable.
On each iteration, we assign the key-value pair to the accumulator
object and
return the result.
accumulator
we return from the first iteration, gets passed as the accumulator
for the second iteration and so on.After the last iteration, the object contains all of the key-value pairs in a sorted order.
Make sure you pass an empty object as the second parameter to the reduce
method - this is the initial value for the accumulator
variable.
Note that this approach does not change the order of the keys in the original object, it creates a new object with sorted keys.
Now you can iterate over the sorted object by using the Object.keys()
and the
forEach()
method.
const obj = {z: 'three', a: 'one', b: 'two'}; // 👇️ ['a', 'b', 'z'] console.log(Object.keys(obj).sort()); const sorted = Object.keys(obj) .sort() .reduce((accumulator, key) => { accumulator[key] = obj[key]; return accumulator; }, {}); Object.keys(sorted).forEach(key => { console.log(key, sorted[key]); // 👉️ a one, b two, z three });
The function we passed to the forEach()
method gets called with each element
(key) in the array.