Aontaigh
Aontaigh

Reputation: 198

Converting Data Into An Array Of Arrays

I currently have data returning in the format from the backend of an application done in PHP (Laravel):

data [
   {
     "Jan": 120,
     "Feb": 283.5,
     "Mar": 10,
     "Apr": 233.92,
     "May": 327.78,
     "Jun": 190.74,
     "Jul": 10,
     "Aug": 10,
     "Sep": 10,
     "Oct": 10,
     "Nov": 10,
     "Dec": 10
   }
]

I want to then graph this data, which is the average order values of a specific company by month, in the front-end using JavaScript (Vue). Though for it to work it needs to be in the format:

new_data [
  ["Jan", 120],
  ["Feb", 283.5],
  ["Mar", 10],
  ["Apr", 233.92],
  ["May", 327.78],
  ["Jun", 190.74],
  ["Jul", 10],
  ["Aug", 10],
  ["Sep", 10],
  ["Oct", 10],
  ["Nov", 10],
  ["Dec", 10]
]

I have seen how to do this for similar things on Stack Overflow (i.e. Object to Array (an array of arrays)) but none fit this exact example.

Upvotes: 1

Views: 77

Answers (3)

Marvin K
Marvin K

Reputation: 344

Since you get an object and not an array from the backend, I find no other solution than looping over the propertys of the object and push the values in a new array. Would look like this:

var newData = [];
Object.keys(data[0]).forEach(function(month) {
    newData.push[month, data[0][month]];
});

Upvotes: 0

Jayanth
Jayanth

Reputation: 816

Classic way to do this is:

var data = [
   {
     "Jan": 120,
     "Feb": 283.5,
     "Mar": 10,
     "Apr": 233.92,
     "May": 327.78,
     "Jun": 190.74,
     "Jul": 10,
     "Aug": 10,
     "Sep": 10,
     "Oct": 10,
     "Nov": 10,
     "Dec": 10
   }
];
var dataArry = new Array();
for(month in data[0]){
  dataArry[dataArry.length] = [month,data[0][month]];
}

In the above code, dataArry hold the object data in a Array format.

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191986

Array.map() to Object.entries() and flatten by spreading into Array.concat():

const data = [{"Jan":120,"Feb":283.5,"Mar":10,"Apr":233.92,"May":327.78,"Jun":190.74,"Jul":10,"Aug":10,"Sep":10,"Oct":10,"Nov":10,"Dec":10}]

const result = [].concat(...data.map(Object.entries))

console.log(result)

Upvotes: 6

Related Questions