Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีจัดเรียงออบเจกต์ของออบเจกต์ตามค่าคีย์ใน 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'    } }