I am new to coding and trying to get this problem right. I tried calling the index of the arrays but it prints out columns. Out dev environment is REPL.it, the virtual machine uses node v10.16.0 and help would be greatly appreciate
Input
tableData = [
["first_name", "last_name", "city", "state"],
["Elisabeth", "Gardenar", "Toledo", "OH"],
["Jamaal", "Du", "Sylvania", "OH"],
["Kathlyn", "Lavoie", "Maumee", "OH"]
]
Desired Output
output = [
{ first_name : "Elisabeth", last_name : "Gardenar", city: "Toledo", state : "OH" },
{ first_name : "Jamaal", last_name : "Du", city: "Sylvania", state : "OH" },
{ first_name : "Kathlyn", last_name : "Lavoie", city: "Maumee", state : "OH" }
]
What I have tried so far is this:
function convertTable(){
var p=console.log;
const [header,...rows] = tableData;
var tableObj = new Object;
var intermediateVal = [];
var finalArr = [];
for(var vals=0;vals<rows.length;vals++){
var row = rows[vals]
for (var key=0,val=0;key<header.length;key++,val++){
tableObj[header[key]]=row[val]
}
p(tableObj)
}
}
convertTable(tableData)
You're pretty close, but you need to create a new object for each row of the result, and then push that object onto the finalArr
array.
There's also no need for both key
and val
variables, since they're always the same.
tableData = [
["first_name", "last_name", "city", "state"],
["Elisabeth", "Gardenar", "Toledo", "OH"],
["Jamaal", "Du", "Sylvania", "OH"],
["Kathlyn", "Lavoie", "Maumee", "OH"]
];
function convertTable() {
var p = console.log;
const [header, ...rows] = tableData;
var finalArr = [];
for (var vals = 0; vals < rows.length; vals++) {
var row = rows[vals]
var tableObj = {};
for (var key = 0; key < header.length; key++) {
tableObj[header[key]] = row[key]
}
finalArr.push(tableObj);
}
p(finalArr)
}
convertTable(tableData)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With