Sometimes, we want to sort or order keys in JavaScript objects.
In this article, we’ll look at how to sort or order keys in JavaScript objects.
How to sort or order keys in JavaScript objects?
To sort or order keys in JavaScript objects, we can use the Object.keys
method and the array sort
and reduce
methods.
For instance, we write
const notSorted = { b: false, a: true };
const sorted = Object.keys(notSorted)
.sort()
.reduce(
(acc, key) => ({
...acc,
[key]: notSorted[key],
}),
{}
);
console.log(sorted);
to call Object.keys
with notSorted
to get the keys of the notSorted
object in an array.
Then we call sort
to sort the keys.
Then we call reduce
with the sorted keys array with a callback to get the keys and values and put them in a new object.
The new object with the sort keys is then returned by reduce
.
Conclusion
To sort or order keys in JavaScript objects, we can use the Object.keys
method and the array sort
and reduce
methods.