Prerna Jain Prerna Jain - 5 months ago 7
Javascript Question

Object Array Formatting

I have an object in this format:

var request = {
"student": [
[
"name",
"age"
],
[
"Tom",
12
],
[
"Jack",
13
]
]
};


I want to transform it into this:

var request = {
"student": [
{
"name": "Tom",
"age": 12
},
{
"name": "Jack",
"age": 13
}
]
}


I tried doing it this way:

var response = [];
var keysCount = req.result[0].length;
var responseCount = req.result.length - 1;
var i = 0,
j = 0,
key;

for (j = 0; j < responseCount; j++) {
for (i = 0; i < keysCount; i++) {
key = req.result[0][i];
response[j][key] = req.result[j + 1][i];
}
}
return response;


But, it is not working as expected.

Answer

It's a matter of looping through the first array and creating an array of objects for all the remaining arrays, using values at matching indexes to create properties on object:

var request = {
  "student": [
    [
      "name",
      "age"
    ],
    [
      "Tom",
      12
    ],
    [
      "Jack",
      13
    ]
  ]
};
// Get the header array
var headers = request.student[0];
// Create the new array but mapping the other entries...
var newArray = request.student.slice(1).map(function(entry) {
  // Create an object
  var newEntry = {};
  
  // Fill it in with the values at matching indexes
  headers.forEach(function(name, index) {
    newEntry[name] = entry[index];
  });
  
  // Return the new object
  return newEntry;
});
console.log(newArray);