 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Regroup JSON array in JavaScript
Suppose, we have a JSON array of objects like this −
const arr = [    {       "id": "03868185",       "month_10": 6,    },    {       "id": "03870584",       "month_6": 2,    },    {       "id": "03870584",       "month_7": 5,    },    {       "id": "51295",       "month_1": 1,    },    {       "id": "51295",       "month_10": 1,    },    {       "id": "55468",       "month_11": 1,    } ]; Here, we can see that the same "id" property is being repeated in some objects. We are required to write a JavaScript function that takes in one such array that contains all the key/value pairs for a specific "id" property grouped in one single object.
Example
The code for this will be −
const arr = [    {       "id": "03868185",       "month_10": 6,    },    {       "id": "03870584",       "month_6": 2,    },    {       "id": "03870584",       "month_7": 5,    },    {       "id": "51295",       "month_1": 1,    },    {       "id": "51295",       "month_10": 1,    },    {       "id": "55468",       "month_11": 1,    } ]; const groupById = (arr = []) => {    const map = {};    const res = [];    arr.forEach(el => {       if(map.hasOwnProperty(el['id'])){          const index = map[el['id']] - 1;          const key = Object.keys(el)[1];          res[index][key] = el[key];       }       else{          map[el['id']] = res.push(el);       }    })    return res; }; console.log(groupById(arr));  Output
And the output in the console will be −
[    { id: '03868185', month_10: 6 },    { id: '03870584', month_6: 2, month_7: 5 },    { id: '51295', month_1: 1, month_10: 1 },    { id: '55468', month_11: 1 } ]Advertisements
 