- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 Separate objects based on properties
Suppose, we have an object like this −
const obj = { 0: { "time": 1, "day": 1, }, 1: { "time": 2, "day": 1, }, 2: { "time": 3, "day": 1, }, 3: { "time": 1, "day": 2, }, 4: { "time": 2, "day": 2, }, 5: { "time": 3, "day": 2, } };
We are required to write a JavaScript function that takes one such object and groups all the key value pairs in separate sub objects that have the same value for the day key.
Output
The output for the above object should be −
const output = { '1': { '1': { time: 1, day: 1 }, '2': { time: 2, day: 1 }, '3': { time: 3, day: 1 } }, '2': { '1': { time: 1, day: 2 }, '2': { time: 2, day: 2 }, '3': { time: 3, day: 2 } } }
Example
The code for this will be −
const obj = { 0: { "time": 1, "day": 1, }, 1: { "time": 2, "day": 1, }, 2: { "time": 3, "day": 1, }, 3: { "time": 1, "day": 2, }, 4: { "time": 2, "day": 2, }, 5: { "time": 3, "day": 2, } }; const groupObject = obj => { let res = {}; res = Object.values(obj).reduce((acc, val) => { if(acc[val['day']] === undefined){ acc[val['day']] ={}; }; acc[val['day']][val['time']] = val; return acc; },{}); return res; }; console.log(groupObject(obj));
Output
The output in the console −
{ '1': { '1': { time: 1, day: 1 }, '2': { time: 2, day: 1 }, '3': { time: 3, day: 1 } }, '2': { '1': { time: 1, day: 2 }, '2': { time: 2, day: 2 }, '3': { time: 3, day: 2 } } }
Advertisements