在JavaScript

时间:2018-02-14 09:54:59

标签: javascript arrays

我是java脚本的新手,并且包含以下对象数组

[{
    firstName: "John",
    lastName: "Doe",
    age: 46
},
{
    firstName: "Mike",
    lastName: "Jeffrey",
    age: 56
}]

我想将这个对象数组转换为多维数组,如下所示

[
    [{
        firstName: "John",
        lastName: "Doe",
        age: 46
    }],
    [{
        firstName: "Mike",
        lastName: "Jeffrey",
        age: 56
    }]
]

我使用以下代码转换为多维数组

var actualResult = [];
var arrayLength = inputObj.length;
for (var i = 0; i < arrayLength; i++) {
    var tempResult = [];
    tempResult.push(inputObj[i]);
    actualResult.push(tempResult);
}

其中inpuObj是我的实际输入。这是实现方案的正确方法吗?

1 个答案:

答案 0 :(得分:6)

您可以使用array#map。遍历每个对象并创建一个数组。

var data = [{firstName: "John",lastName: "Doe",age: 46},{firstName: "Mike",lastName: "Jeffrey",age: 56}],
    result = data.map(o => [o]);
console.log(result);