키를 문자열 리터럴로, 그 값을 객체로 가진 객체가 다음과 같이 있다고 가정해 보겠습니다. -
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' } }