Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript: Sort Object of Objects
Suppose we have an Object of Objects like this −
const obj = {
"CAB": {
name: 'CBSSP',
position: 2
},
"NSG": {
name: 'NNSSP',
position: 3
},
"EQU": {
name: 'SSP',
position: 1
}
};
We are required to write a JavaScript function that takes in one such array and sorts the sub-objects on the basis of the 'position' property of sub-objects (either in increasing or decreasing order).
Example
The code for this will be −
const obj = {
"CAB": {
name: 'CBSSP',
position: 2
},
"NSG": {
name: 'NNSSP',
position: 3
},
"EQU": {
name: 'SSP',
position: 1
}
};
const sortByPosition = obj => {
const order = [], res = {};
Object.keys(obj).forEach(key => {
return order[obj[key]['position'] - 1] = key;
});
order.forEach(key => {
res[key] = obj[key];
});
return res;
}
console.log(sortByPosition(obj));
Output
And the output in the console will be −
{
EQU: { name: 'SSP', position: 1 },
CAB: { name: 'CBSSP', position: 2 },
NSG: { name: 'NNSSP', position: 3 }
}Advertisements