Skip to content Skip to sidebar Skip to footer

Convert Object To Multi-dimensional Array - Javascript

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',

Solution 1:

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 =>newArray(v, myObj[v]));
    
    console.log(JSON.stringify(myArray));

Solution 2:

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

Post a Comment for "Convert Object To Multi-dimensional Array - Javascript"