How to Sort object of objects by its key value JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we have an object with keys as string literals and their values as objects as well like this −

const companies = {
   'landwaves ltd': {employees: 1200, worth: '1.2m', CEO: 'Rajiv Bansal'},
   'colin & co': {employees: 200, worth: '0.2m', CEO: 'Sukesh Maheshwari'},
   'motilal biscuits': {employees: 975, worth: '1m', CEO: 'Rahul Gupta'},
   'numbtree': {employees: 1500, worth: '1.5m', CEO: 'Jay Kumar'},
   'solace pvt ltd': {employees: 1800, worth: '1.65m', CEO: 'Arvind Sangal'},
   'ambicure': {employees: 170, worth: '0.1m', CEO: 'Preetam Chawla'},
   'dis n dat': {employees: 540, worth: '1m', CEO: 'Mohit Sharma'},
}

We are required to write a function that sorts the object according to its keys and returns it.

Example

const companies = {
   'landwaves ltd': {employees: 1200, worth: '1.2m', CEO: 'Rajiv Bansal'},
   'colin & co': {employees: 200, worth: '0.2m', CEO: 'Sukesh Maheshwari'},
   'motilal biscuits': {employees: 975, worth: '1m', CEO: 'Rahul Gupta'},
   'numbtree': {employees: 1500, worth: '1.5m', CEO: 'Jay Kumar'},
   'solace pvt ltd': {employees: 1800, worth: '1.65m', CEO: 'Arvind Sangal'},
   'ambicure': {employees: 170, worth: '0.1m', CEO: 'Preetam Chawla'},
   'dis n dat': {employees: 540, worth: '1m', CEO: 'Mohit Sharma'},
};
const sortKeys = (obj) => {
   return Object.assign(...Object.entries(obj).sort().map(([key, value])
   => {
      return {
         [key]: value
      }
   }));
};
console.log(sortKeys(companies));

Output

The output in the console will be −

{
   ambicure: { employees: 170, worth: '0.1m', CEO: 'Preetam Chawla' },
   'colin & co': { employees: 200, worth: '0.2m', CEO: 'Sukesh Maheshwari'},
   'dis n dat': { employees: 540, worth: '1m', CEO: 'Mohit Sharma' },
   'landwaves ltd': { employees: 1200, worth: '1.2m', CEO: 'Rajiv Bansal' },
   'motilal biscuits': { employees: 975, worth: '1m', CEO: 'Rahul Gupta' },
   numbtree: { employees: 1500, worth: '1.5m', CEO: 'Jay Kumar' },
   'solace pvt ltd': { employees: 1800, worth: '1.65m', CEO: 'Arvind Sangal'
   }
}
raja
Published on 21-Aug-2020 17:24:07
Advertisements