Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Retrieving object's entries in order with JavaScript?
In JavaScript, object properties don't maintain insertion order for numeric keys, but we can retrieve entries in sorted order using Object.keys() and sort() methods.
The Problem
Consider an object with numeric keys that aren't in sequential order:
const subjectDetails = {
102: "Java",
105: "JavaScript",
104: "MongoDB",
101: "MySQL"
};
console.log("Original object:");
console.log(subjectDetails);
Original object:
{
'101': 'MySQL',
'102': 'Java',
'104': 'MongoDB',
'105': 'JavaScript'
}
Using Object.fromEntries() with Sorted Keys
We can create a new object with entries sorted by keys using Object.fromEntries():
const subjectDetails = {
102: "Java",
105: "JavaScript",
104: "MongoDB",
101: "MySQL"
};
const orderSubjects = Object.fromEntries(
Object.keys(subjectDetails).sort().map((k) => {
return [k, subjectDetails[k]];
})
);
console.log("Sorted by keys:");
console.log(orderSubjects);
Sorted by keys:
{
'101': 'MySQL',
'102': 'Java',
'104': 'MongoDB',
'105': 'JavaScript'
}
Alternative Method: Using Object.entries()
You can also sort entries directly and reconstruct the object:
const subjectDetails = {
102: "Java",
105: "JavaScript",
104: "MongoDB",
101: "MySQL"
};
const sortedEntries = Object.entries(subjectDetails)
.sort(([a], [b]) => a.localeCompare(b));
const orderedObject = Object.fromEntries(sortedEntries);
console.log("Using Object.entries():");
console.log(orderedObject);
Using Object.entries():
{
'101': 'MySQL',
'102': 'Java',
'104': 'MongoDB',
'105': 'JavaScript'
}
Sorting by Values
To sort by values instead of keys:
const subjectDetails = {
102: "Java",
105: "JavaScript",
104: "MongoDB",
101: "MySQL"
};
const sortedByValues = Object.fromEntries(
Object.entries(subjectDetails)
.sort(([,a], [,b]) => a.localeCompare(b))
);
console.log("Sorted by values:");
console.log(sortedByValues);
Sorted by values:
{
'102': 'Java',
'105': 'JavaScript',
'104': 'MongoDB',
'101': 'MySQL'
}
Conclusion
Use Object.fromEntries() with Object.keys().sort() to retrieve object entries in key order. For value-based sorting, combine Object.entries() with custom sort functions.
Advertisements
