问题
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:
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));
回答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));
来源:https://stackoverflow.com/questions/43690246/convert-object-to-multi-dimensional-array-javascript