#javascript #arrays #json #reactjs
#javascript #массивы #json #reactjs
Вопрос:
У меня есть эти данные Json:
[
{
"serial_number": "test",
"added_at": "2021-02-05T18:58:43.382943Z",
"ser_mod": [
{
"added_at": "2021-02-06T02:15:51.513446Z",
"module": "test",
"time": "0.05"
},
{
"added_at": "2021-02-09T00:44:46.254122Z",
"module": "test",
"time": "2.23"
},
{
"added_at": "2021-02-09T00:44:58.010508Z",
"module": "test",
"time": "2.23"
}
]
},
{
"serial_number": "test2",
"added_at": "2021-02-09T10:04:38.394083Z",
"ser_mod": [
{
"added_at": "2021-02-09T10:05:43.605226Z",
"module": "test2",
"time": "2.23"
}
]
}
]
Я хотел бы отобразить serial_number
и последнюю time
<React.Fragment>
<Container maxWidth='md' component='main'>
<Grid container spacing={5} alignItems='flex-end'>
{modules.map((module) => {
return (
<Grid item key={module.serial_number} xs={12} md={12}>
<Card className={classes.card}>
<CardContent className={classes.cardContent}>
<Typography
gutterBottom
variant='h6'
component='h1'
className={classes.postTitle}
>
Serial Number: {module.serial_number}
</Typography>
<div className={classes.postText}>
<Typography component='p' color='textPrimary' />
<Typography variant='p' color='textSecondary'>
Time: {module.ser_mod.time}
</Typography>
</div>
</CardContent>
</Card>
</Grid>
);
})}
</Grid>
</Container>
</React.Fragment>;
Но я не могу заставить это работать; время отображается не так, как ожидалось. Это то, что я получаю:
Что я должен сделать, чтобы решить эту проблему?
Комментарии:
1.
ser_mod
представляет собой массив, содержащий несколько объектов соtime
свойствами. Что вы хотите?
Ответ №1:
Вам нужно выбрать только последний ser_mod
элемент.
Изменить с:
<Typography variant="p" color="textSecondary">
Time: {module.ser_mod.time}
</Typography>
Для:
<Typography variant="p" color="textSecondary">
Time: {module.ser_mod[ module.ser_mod.length - 1].time}
</Typography>
Несколько дополнительных советов
- Упрощение
modules.map
обратного вызова безreturn
:
{modules.map((module) => (
/* ... */
)}
- Деструктура
module
для оптимизации и уточнения:
{modules.map(({serial_number, ser_mod}) => (
<Grid item key={serial_number} xs={12} md={12}>
/* ... */
</Grid>
)}
Комментарии:
1. Откуда вы знаете? Почему бы ему не быть первым вместо этого?
2. @JaredSmith Это в исходном вопросе:
i will like to display serial_number and latest time
.