1

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.

Aontaigh
  • 178
  • 1
  • 3
  • 13

3 Answers3

6

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)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • He isn't asking for a flattened structure? So I guess `data.map(Object.entries) ` will do? Still a valid enough answer if you ask me, so upvoted. – Alex Apr 03 '18 at 09:30
  • Indeed. However, in the question the result is flattened as it doesn't contain a subarray wrapping the items. – Ori Drori Apr 03 '18 at 09:31
  • Oh right, I missed that. So he actually is asking for a flattened structure. – Alex Apr 03 '18 at 09:35
0

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]];
});
Marvin K
  • 334
  • 3
  • 14
0

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.

Jayanth
  • 746
  • 6
  • 17