Hi I am new in React and Firebase database. I am getting error while try to print data using map.

basically I am using firebase-database and I have displayed the list of all the days for the project including the total amount of hours. under each day I want to show the worker name including the amount of hours worked for single user for that day. Here is Screen-shot

Here is my Firebase Data

as you see in Database under 0 key users details are given but not under key 1 and 2
now I am getting error while print user_name while try to access row.users.map() as given under code.
<Table className="MyTable">
<TableHead>
<TableRow>
<StyledTableCell>Dato</StyledTableCell>
<StyledTableCell>User Name</StyledTableCell>
<StyledTableCell align="right">Timer</StyledTableCell>
</TableRow>
</TableHead>
<TableBody>
{props.data.dayWiseHours.map(row => (
<StyledTableRow key={row.date}>
<StyledTableCell component="th" scope="row">
{`${row.date}\n`}
</StyledTableCell>
<StyledTableCell component="td" scope="row">
{ row && row.users &&
row.users.map((subData, subindex) =>
<span key={subindex}>{subData.user_name}</span>
)
}
</StyledTableCell>
<StyledTableCell align="right">
{`${row.hour}\n`}
</StyledTableCell>
</StyledTableRow>
))}
</TableBody>
</Table>
If I try under given code its working fine
<TableBody>
{props.data.dayWiseHours.map(row => (
<StyledTableRow key={row.date}>
<StyledTableCell component="th" scope="row">
{`${row.date}\n`}
</StyledTableCell>
<StyledTableCell component="td" scope="row">
{ row && row.users && row.users['-LjuTOzAhVpku-hDFUJ7'].user_name ? row.users['-LjuTOzAhVpku-hDFUJ7'].user_name : "--" }
</StyledTableCell>
<StyledTableCell align="right">
{`${row.hour}\n`}
</StyledTableCell>
</StyledTableRow>
))}
</TableBody>
but key : row.users['-LjuTOzAhVpku-hDFUJ7'] will not be always same.
Thanks
Looks like row.users is an Object, you can use map on Array only. To iterate over an Object you can do something like this:
const object1 = {
a: 'somestring',
b: 42,
c: false
};
Object.keys(object1).map((key) => {
console.log('key:', key);
console.log('value:', object1[key]);
});
First create an Array of the keys of the Object, then map that Array.
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