2

I have an object like this:

var myObj = {
    a: 1,
    b: 2,
    c: 3,
    d: 4
};

And i want to convert that object to a multi-dimensional array like this:

var myArray = [['a', 1], ['b', 2], ['c', 3], ['d', 4]];

How could i achieve this?

1
  • 1
    var arr = Object.keys(myObj).map(k => [k, myObj[k]]); Commented Apr 28, 2017 at 23:52

2 Answers 2

5

You can use Object.entries function.

var myObj = { a: 1, b: 2, c: 3, d: 4 },
    myArray = Object.entries(myObj);
    
    console.log(JSON.stringify(myArray));

...or Object.keys and Array#map functions.

var myObj = { a: 1, b: 2, c: 3, d: 4 },
    myArray = Object.keys(myObj).map(v => new Array(v, myObj[v]));
    
    console.log(JSON.stringify(myArray));

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

2 Comments

NOTE: Object.entries is not ubiquitously implemented - it is still experimental. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
You saved my life!, I didn't remember it!
1

var myArray = [];
var myObj = { a: 1, b: 2, c: 3, d: 4 };
for(var key in myObj) {
  myArray.push([key, myObj[key]]);
}
console.log(JSON.stringify(myArray));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.