首页 > 解决方案 > 如何遍历对象数组并仅显示子组件中的最新值?

问题描述

我正在尝试构建一个接收名为tag1,tag2,tag3. 该数据来自我的数据库,其示例如下所示。

我正在尝试遍历标记为 temperature 的值,并显示 API 下的最新值Temperature

但目前它会同时输出每一个温度读数。

那么我如何只显示一个最新的值呢?

const Cards = ({ tag1, tag2, tag3 }) => {
    console.log(tag1);
    return (
        <div className={styles.container}>
            <Grid container spacing={3} justify="center">
                <Grid item component={Card}>
                    <CardContent>
                        <Typography color="textPrimary" gutterBottom>
                            Tag 1
                        </Typography>
                        <Typography variant="body2">
                            Temperature:
                            {tag1.map(tag => tag.temperature)}
                        </Typography>
                        <Typography variant="body2"></Typography>
                        <Typography variant="body2"></Typography>
                    </CardContent>
                </Grid>
            </Grid>
        </div>
    );
};

tag1:来自 API 的对象数组

tag1:
(261) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]

tag1[0]:
0:
accuracy: "15.455"
eventId: "a7e81ca3-b840-4bb1-b41f-821722da4a5b"
humidity: "50"
latitude: "2.708813"
location: {accuracy: {…}, latitude: {…}, longitude: {…}}
longitude: "102.0083215"
name: "Tag1"
tags: {humidityOffset: {…}, rssi: {…}, dataFormat: {…}, movementCounter: {…}, updateAt: {…}, …}
temperature: "28.26"
time: "2020-10-18T01:46:00+0800"
__proto__: Object

标签: javascriptreactjs

解决方案


首先根据时间对数组进行倒序排序

let sortedTags = array.sort((a,b)=> b.time - a.time);

然后显示第一个元素

<Typography variant="body2">
       Temperature :  {sortedTags[0].temparature}
</Typography>

推荐阅读