Hello all,
I’m working on a repl.it program for Code Platoon.
The directions are:
The variable tableData below represents data as it might appear in a table or spreadsheet. The first array contains column names and the rest of the arrays are rows of data. Write a function convertTable that converts the data in a nested array like tableData to an array of objects that matches the output below. Your function should work for any array formatted like tableData, meaning it should always use the first array given as the keys and the rest of the arrays as values.
For example:
const tableData = [
["first_name", "last_name", "city", "state"],
["Elisabeth", "Gardenar", "Toledo", "OH"],
["Jamaal", "Du", "Sylvania", "OH"],
["Kathlyn", "Lavoie", "Maumee", "OH"]
]
convertTable(tableData)
// The return is below
[
{ 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" }
]
My program:
// Write your convertTable function here
const tableData = [
["first_name", "last_name", "city", "state"],
["Elisabeth", "Gardenar", "Toledo", "OH"],
["Jamaal", "Du", "Sylvania", "OH"],
["Kathlyn", "Lavoie", "Maumee", "OH"]
];
var row =[];
function convertTable(arr) {
for (i = 0; i < arr.length; i++) {
var fname = arr[i+1][0], lname = arr[i+1][1], city = arr[i+1][2], state = arr[i+1][3];
console.log(arr[0][0] + " : \"" + fname + "\", " + arr[0][1] + " : \"" + lname + "\", " + arr[0][2] + " : \"" + city + "\", " + arr[0][3] + " : \"" + state + "\"");
row = (arr[0][0] + " : \"" + fname + "\", " + arr[0][1] + " : \"" + lname + "\", " + arr[0][2] + " : \"" + city + "\", " + arr[0][3] + " : \"" + state + "\"");
}
return row;
}
convertTable(tableData);
The console error:
Native Browser JavaScript
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”
TypeError: Cannot read property ‘0’ of undefined
at convertTable:14:27
at eval:20:1
at eval
at new Promise
Thanks for your help in advance!!!