Retrieving object's entries in order with JavaScript?


Let’s say the following is our object −

const subjectDetails ={
   102:"Java",
   105:"JavaScript",
   104:"MongoDB",
   101:"MySQL"
};

Use sort() method to retrieve object’s entry in order −

const orderSubjects =
Object.fromEntries(Object.keys(subjectDetails).sort().map((k) => {
   return [k, subjectDetails[k]];
}));

Example

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(orderSubjects);

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo146.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo146.js{
   '101': 'MySQL',
   '102': 'Java',
   '104': 'MongoDB',
   '105': 'JavaScript'
}

Updated on: 11-Sep-2020

206 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements