javascript - 如何遍历对象数组并仅显示子组件中的最新值?
问题描述
我正在尝试构建一个接收名为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
解决方案
首先根据时间对数组进行倒序排序
let sortedTags = array.sort((a,b)=> b.time - a.time);
然后显示第一个元素
<Typography variant="body2">
Temperature : {sortedTags[0].temparature}
</Typography>
推荐阅读
- java - PHP 没有从带有 AsyncTask 的 POST 请求中接收数据
- java - 外部存储:无法查询我有读取权限的文件
- coq - SsrReflect 和 setoid 重写
- spring-boot - Spring Integration JMS - Spring 代码确实在 RuntimeException 上提交
- awk - 比较不同文件中的特定列并打印不匹配的列
- android - 调用创建套接字只是挂起并且不连接
- javascript - 使用 React 在 Codepen 上未呈现按钮
- tensorflow - 图像检测和分类 - 一般方法?
- python - 通过基于 chi^2=2 设置计算 python curvefit/polyfit 中的错误
- python-3.x - 不知道如何在列表中使用“if in”