Extract arrays separately from array of Objects in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 ]
}
raja
Published on 20-Nov-2020 10:33:08
Advertisements