Convert Array of Objects to Multi Dimensional Array in JavaScript

user8363477 Source

I an new to java script and have array of objects as following

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

I would like to convert this array of objects to multi-dimensional array as following

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

I am using the following code to convert to multi dimension array

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

where inpuObj is my actual input.Is this the correct way of achieving the scenario?

javascriptarrays

Answers

answered 6 days ago Hassan Imam #1

You can use array#map. Iterate through each object and create an array.

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

comments powered by Disqus