如何按键值 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'
}
}
以上是 如何按键值 JavaScript 对对象的对象进行排序 的全部内容, 来源链接: utcz.com/z/331891.html