- 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
Read by key and parse as JSON in JavaScript
Suppose, we have a JSON array like this −
const arr = [{ "data": [ { "W": 1, "A1": "123" }, { "W": 1, "A1": "456" }, { "W": 2, "A1": "4578" }, { "W": 2, "A1": "2423" }, { "W": 2, "A1": "2432" }, { "W": 2, "A1": "24324" } ] }];
We are required to write a JavaScript function that takes in one such array and converts it to the following JSON array −
[ { "1": [ { "A1": "123" }, { "A1": "456" } ] }, { "2": [ { "A1": "4578" }, { "A1": "2423" }, { "A1": "2432" }, { "A1": "24324" } ] } ];
Example
const arr = [{ "data": [ { "W": 1, "A1": "123" }, { "W": 1, "A1": "456" }, { "W": 2, "A1": "4578" }, { "W": 2, "A1": "2423" }, { "W": 2, "A1": "2432" }, { "W": 2, "A1": "24324" } ] }]; const groupJSON = (arr = []) => { const preCombined = arr[0].data.reduce((acc, val) => { acc[val.W] = acc[val.W] || []; acc[val.W].push({ A1: val.A1 }); return acc; }, {}); const combined = Object.keys(preCombined).reduce((acc, val) => { const temp = {}; temp[val] = preCombined[val]; acc.push(temp); return acc; }, []); return combined; }; console.log(JSON.stringify(groupJSON(arr), undefined, 4));
Output
And the output in the console will be −
[ { "1": [ { "A1": "123" }, { "A1": "456" } ] }, { "2": [ { "A1": "4578" }, { "A1": "2423" }, { "A1": "2432" }, { "A1": "24324" } ] } ]
Advertisements