I need to transform the following structure using React.
export const bodyRows = [
{
row: [{ cell: "Name" }, { cell: "Allan, Trent" }, { cell: "Smith, Nathan" }, { cell: "Howard, Greg" }],
},
{
row: [{ cell: "Student ID" }, { cell: 332 }, { cell: 333 }, { cell: 334 }, { cell: 335 }, { cell: 356 }],
},
{
row: [{ cell: "Studkey" }, { cell: "333-B" }, { cell: "334-B" }, { cell: "335-B" }, { cell: "336-B" }, { cell: "332-B" }],
},
{
row: [{ cell: "Name" }, { cell: "Smith, Trent" }, { cell: "Ryan, Nathan" }, { cell: "Johnson, Greg" }],
},
{
row: [{ cell: "Student ID" }, { cell: 232 }, { cell: 233 }, { cell: 234 }, { cell: 235 }, { cell: 256 }],
},
{
row: [{ cell: "Studkey" }, { cell: "233-B" }, { cell: "234-B" }, { cell: "235-B" }, { cell: "236-B" }, { cell: "232-B" }],
},
{
row: [{ cell: "Name" }, { cell: "Lewis, Trent" }, { cell: "Roberts, Nathan" }, { cell: "Roberts, Greg" }],
},
{
row: [{ cell: "Student ID" }, { cell: 132 }, { cell: 133 }, { cell: 134 }, { cell: 135 }, { cell: 156 }],
},
{
row: [{ cell: "Studkey" }, { cell: "133-B" }, { cell: "134-B" }, { cell: "135-B" }, { cell: "136-B" }, { cell: "132-B" }],
},
];
I have the following and I can’t get it working correctly. Could anyone please recommend how to solve this?
const bodyRows = studentHistory.map((students) => ({
row: [{ cell: "Name" }, { cell: students.studentName }],
row: [{ cell: "Student ID" }, { cell: students.studentId }],
row: [{ cell: "Studkey" }, { cell: students.studentHistoryId }],
}));
2
Answers
For that you need to use Array.reduce method.
I see you’re trying to transform your data into a table, but I think there’s a bit of confusion with your code:
You’re overwriting the
row
property in your.map()
function, so only the lastrow
will show up. Were you trying to have multiple rows in the same object?Also, could you clarify how you want the table structured? From the example image, it looks like you want the data to display horizontally with ‘Name’, ‘Student ID’, and ‘Studkey’ as the headers, but I just want to be sure I’m on the right track.
Once I have a bit more context, I’ll try to help you out with the solution