Reputation: 609
I have a variable that is returning an array of arrays, with each item in each array in double quotes.
var arrayOfArrays = [
[ "Name", "Age", "Address" ],
[ "A", "43", "CA" ],
[ "B", "23", "VA" ],
[ "C", "24", "NY" ]
]
I need to convert this to the following:
var arrayOfObjects = [
{"Name":"A", "Age":"43", "Address":"CA"},
{"Name":"B", "Age":"23", "Address":"VA"},
{"Name":"C", "Age":"24", "Address":"NY"}
]
Upvotes: 0
Views: 91
Reputation: 848
Extract the headers and use the map
function:
var headers = arrayOfArrays.splice(0,1)[0];
var arrayOfObjects = arrayOfArrays.map(function(e) {
var o = {};
headers.forEach(function(h, index) {
o[h] = e[index];
})
return o;
});
Link HERE.
Upvotes: 0
Reputation: 38161
here is simple demo.
var arrayOfArrays = [
["Name", "Age", "Address"],
["A", "43", "CA"],
["B", "23", "VA"],
["C", "24", "NY"]
];
function testConvert(arr) {
var result = [];
var keys = arr[0];
for (var i = 1; i < arr.length; i++) {
var item = {};
item[keys[0]] = arr[i][0];
item[keys[1]] = arr[i][1];
item[keys[2]] = arr[i][2];
result.push(item);
}
return result;
}
console.log(testConvert(arrayOfArrays));
Upvotes: 1