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?

Vadim Kotov
8,2848 gold badges51 silver badges63 bronze badges
asked Apr 28, 2017 at 23:38
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));

answered Apr 28, 2017 at 23:39
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));

answered Apr 28, 2017 at 23:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.