Convert array of object to array of array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have the following array of objects −

const arr = [
   {"2015":11259750.05},
   {"2016":14129456.9}
];

We are required to write a JavaScript function that takes in one such array. The function should prepare an array of arrays based on the input array.

Therefore, the output for the above array should look like −

const output = [
   [2015,11259750.05],
   [2016,14129456.9]
];

Example

The code for this will be −

const arr = [
   {"2015":11259750.05},
   {"2016":14129456.9}
];
const mapToArray = (arr = []) => {
   const res = [];
   arr.forEach(function(obj,index){
      const key= Object.keys(obj)[0];
      const value = parseInt(key, 10);
      res.push([value, obj[key]]);
   });
   return res;
};
console.log(mapToArray(arr));

Output

And the output in the console will be −

[ [ 2015, 11259750.05 ], [ 2016, 14129456.9 ] ]
raja
Published on 24-Nov-2020 15:35:42
Advertisements