0

Currently, my script produces an object with a format as follows:

{name: numerical value, name: numerical value}

Highcharts, the charting library I am using requires data to be in an array of arrays with two values, example:

[ ["name", "numerical value"], ["name", "numerical value"], ["name", "numerical value"] ]

How can I convert my javascript object into arrays within an array?

3 Answers 3

3

Loop through the object's keys, creating a new pair for each:

var obj = { name: 3, name2: 4 /* etc. */ };
var data = [];

for ( f in obj )
{
  var pair = [ f, obj[f] ];
  data.push(pair);
}

Or, a less-verbose version of that loop:

for ( f in obj )
{
  data.push( [ f, obj[f] ] );
}

var obj = { name: 3, name2: 4, name3: 72 };
var data = [];

for ( f in obj )
{
  data.push( [ f, obj[f] ] );
}

console.log( JSON.stringify(data) );

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

Comments

1

You can use Object.keys and map

var data = {name: 'numerical value', name1: 'numerical value'};

var res = Object.keys(data).map(function (el) {
  return [el, data[el]];
});

console.log(res);

Example

2 Comments

Keep in mind that if you're supporting IE8 or earlier (among other older browsers), you'll need to bring your own implementation of keys() and map(). Examples are provided at the linked pages.
Thanks! Very nice and compact answer.
0

If you read this in 2018 you can use Object.entries method

function convertObjectToList(obj) {
  return Object.entries(obj);
}

Comments

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.