
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Extract Arrays Separately from Array of Objects in JavaScript
Suppose, we have an array of objects like this −
const arr = [{ name : 'Client 1', total: 900, value: 12000 }, { name : 'Client 2', total: 10, value: 800 }, { name : 'Client 3', total: 5, value : 0 }];
We are required to write a JavaScript function that takes in one such array and extracts a separate array for each object property.
Therefore, one array for the name property of each object, one for total and one for value. If there existed more properties, we would have separated more arrays.
Example
The code for this will be −
const arr = [{ name : 'Client 1', total: 900, value: 12000 }, { name : 'Client 2', total: 10, value: 800 }, { name : 'Client 3', total: 5, value : 0 }]; const separateOut = arr => { if(!arr.length){ return []; }; const res = {}; const keys = Object.keys(arr[0]); keys.forEach(key => { arr.forEach(el => { if(res.hasOwnProperty(key)){ res[key].push(el[key]) }else{ res[key] = [el[key]]; }; }); }); return res; }; console.log(separateOut(arr));
Output
And the output in the console will be −
{ name: [ 'Client 1', 'Client 2', 'Client 3' ], total: [ 900, 10, 5 ], value: [ 12000, 800, 0 ] }
Advertisements