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?
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));
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.