如何根据键值 JavaScript 对对象中的对象进行排序


假设,我们有一个对象的键作为字符串文本,其值也作为对象,如下所示 -

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

输出

控制台中的输出为 -

{
   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'
   }
}

更新于: 21-8-2020

560 次浏览

开启 职业生涯

通过完成课程获得认证

开始
广告