繁体   English   中英

如何在 React 中显示 json 数据的特定键

[英]How to display specific keys of json data in React

我有这个 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>;

但我无法完成这项工作; 时间未按预期显示。 这就是我得到的:

我应该怎么做才能解决这个问题?

您只需要选择最后一个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>
)}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM