- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
JSON group object in JavaScript
Suppose, we have an array of objects like this −
const arr = [ { 'name': 'JON', 'flight':100, 'value': 12, type: 'uns' }, { 'name': 'JON', 'flight':100, 'value': 35, type: 'sch' }, { 'name': 'BILL', 'flight':200, 'value': 33, type: 'uns' }, { 'name': 'BILL', 'flight':200, 'value': 45, type: 'sch' } ];
We are required to write a JavaScript function that takes in one such array of objects. The function should map remove the 'value' and 'type' keys from the objects and add their values as key value pairs to the respective objects.
Therefore, the output for the above input should look like this −
const output = [ { 'name': 'JON', 'flight':100, 'uns': 12, 'sch': 35 }, { 'name': 'BILL', 'flight':200, 'uns': 33, 'sch': 45} ];
Output
The code for this will be −
const arr = [ { 'name': 'JON', 'flight':100, 'value': 12, type: 'uns' }, { 'name': 'JON', 'flight':100, 'value': 35, type: 'sch' }, { 'name': 'BILL', 'flight':200, 'value': 33, type: 'uns' }, { 'name': 'BILL', 'flight':200, 'value': 45, type: 'sch' } ]; const groupArray = (arr = []) => { const res = arr.reduce(function (hash) { return function (r, o) { if (!hash[o.name]) { hash[o.name] = { name: o.name, flight: o.flight }; r.push(hash[o.name]); } hash[o.name][o.type] = (hash[o.name][o.type] || 0) + o.value; return r; } }(Object.create(null)), []); return res; }; console.log(groupArray(arr));
Output
And the output in the console will be −
[ { name: 'JON', flight: 100, uns: 12, sch: 35 }, { name: 'BILL', flight: 200, uns: 33, sch: 45 } ]
- Related Articles
- JavaScript group a JSON object by two properties and count
- Group Similar Items in JSON in JavaScript
- How to group JSON data in JavaScript?
- Print JSON nested object in JavaScript?
- Flattening a JSON object in JavaScript
- Sorting a JSON object in JavaScript
- Deep Search JSON Object JavaScript
- How to convert JSON text to JavaScript JSON object?
- How to parse JSON object in JavaScript?
- Constructing a nested JSON object in JavaScript
- Create array from JSON object JavaScript
- Group by JavaScript Array Object
- From JSON object to an array in JavaScript
- Removing property from a JSON object in JavaScript
- Merge and group object properties in JavaScript

Advertisements