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.

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Indeed. However, in the question the result is flattened as it doesn't contain a subarray wrapping the items.
Oh right, I missed that. So he actually is asking for a flattened structure.
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.

Comments

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]];
});

2 Comments

I guess Object.keys(data[0]) works instead of Object.keys(data). Not sure though.
For this case you're right. Updated. The solution from Ori Drori is a little bit more elegant

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.