キー値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でオブジェクトを作成してそのプロパティにアクセスするにはどうすればよいですか?
以下は、オブジェクトを作成し、JavaScriptでそのプロパティにアクセスするコードです- 例 <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <st
-
JavaScriptの値に基づいてオブジェクトをグループ化する方法は?
以下は、JavaScriptの値に基づいてオブジェクトをグループ化するコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>