

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Combine array of objects in JavaScript
Suppose, we have an array of objects that contains data about some students like this −
const arr = [{ name: 'A', idNo: 1, marks: { math: 98, sci: 97, eng: 89 } }, { name: 'B', idNo: 2, marks: { math: 88, sci: 87, eng: 79 } }, { name: 'C', idNo: 3, marks: { math: 87, sci: 98, eng: 91 } }];
We are required to write a JavaScript function that takes in one such array.
Our function should then prepare an object of properties, one property for each object id the objects currently have.
Therefore, for the above array, the output should look like −
const output = { name: [A, B, C], idNo: [1, 2, 3], marks: [{ math: 98, sci: 97, eng: 89 }, { math: 88, sci: 87, eng: 79 }, { math: 87, sci: 98, eng: 91 }] };
Example
The code for this will be −
const arr = [{ name: 'A', idNo: 1, marks: { math: 98, sci: 97, eng: 89 } }, { name: 'B', idNo: 2, marks: { math: 88, sci: 87, eng: 79 } }, { name: 'C', idNo: 3, marks: { math: 87, sci: 98, eng: 91 } }]; const combineMarks = (arr = []) => { let res = []; res = arr.reduce((acc, val) => { Object.keys(val).forEach(el => { if (!acc[el]) { acc[el] = []; }; acc[el].push(val[el]) }); return acc; }, {}); return res; }; console.log(combineMarks(arr));
Output
And the output in the console will be −
{ name: [ 'A', 'B', 'C' ], idNo: [ 1, 2, 3 ], marks: [ { math: 98, sci: 97, eng: 89 }, { math: 88, sci: 87, eng: 79 }, { math: 87, sci: 98, eng: 91 } ] }
- Related Questions & Answers
- How to combine two arrays into an array of objects in JavaScript?
- Manipulating objects in array of objects in JavaScript
- Combine objects and delete a property with JavaScript
- JavaScript - length of array objects
- Compare array of objects - JavaScript
- Filtering array of objects in JavaScript
- Array of objects to array of arrays in JavaScript
- Creating an array of objects based on another array of objects JavaScript
- Converting array of objects to an object of objects in JavaScript
- Update array of objects with JavaScript?
- Loop backward in array of objects JavaScript
- Using methods of array on array of JavaScript objects?
- Search from an array of objects via array of string to get array of objects in JavaScript
- Filter JavaScript array of objects with another array
- Convert object of objects to array in JavaScript
Advertisements