Array of objects to array of arrays in JavaScript


Suppose, we have an array of objects like this −

const arr = [
   {"Date":"2014","Amount1":90,"Amount2":800},
   {"Date":"2015","Amount1":110,"Amount2":300},
   {"Date":"2016","Amount1":3000,"Amount2":500}
];

We are required to write a JavaScript function that takes in one such array and maps this array to another array that contains arrays instead of objects.

Therefore, the final array should look like this −

const output = [
   ['2014', 90, 800],
   ['2015', 110, 300],
   ['2016', 3000, 500]
];

Example

The code for this will be −

const arr = [
   {"Date":"2014","Amount1":90,"Amount2":800},
   {"Date":"2015","Amount1":110,"Amount2":300},
   {"Date":"2016","Amount1":3000,"Amount2":500}
];
const arrify = (arr = []) => {
   const res = [];
   const { length: l } = arr;
   for(let i = 0; i < l; i++){
      const obj = arr[i];
      const subArr = Object.values(obj);
      res.push(subArr);
   };
   return res;
};
console.log(arrify(arr));

Output

And the output in the console will be −

[ [ '2014', 90, 800 ], [ '2015', 110, 300 ], [ '2016', 3000, 500 ] ]

Updated on: 23-Nov-2020

643 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements