1

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?

3
  • 2
    can I ask why do you want to achieve that? You're still going to have to access a dictionary in the i position of the first array anyway Commented Feb 14, 2018 at 9:56
  • Why do you want to do this? Commented Feb 14, 2018 at 9:57
  • @Shinra tensei I am using a tool where the underlying components uses javascript and this is one of the scenario I want to achieve in order to process data Commented Feb 14, 2018 at 10:02

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

what if I get the payload dynamically which is stored in msg variable then is it msg, result =data.map(o=>[o]);?
You need to make sure that your data is array, in your code it is undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.