javascript - 我想替换数组中对象的值?
问题描述
我的数组中有一个时间戳,我从中删除了 UTC 字母,我想用“新”时间戳(没有 UTC)替换旧时间戳也许有更简单的方法来删除?
所以我试图用 .forEach 和 .map 循环我的数据,试图替换它,但仍然没有弄清楚如何做到这一点。我已经看过一堆关于此的 Stackoverflow 线程,但还没有找到我可以开始工作的解决方案....显然遗漏了一些东西或写错了一些东西。
那么谁能指导我如何以最好的方式解决这个问题?
const data = [
{
timestamp: "2019-03-01 09:00:00UTC",
url: "/blub.html",
userid: "12345"
},
{
timestamp: "2019-03-01 09:00:00UTC",
url: "/cont.html ",
userid: "12346"
},
{
timestamp: "2019-03-01 10:00:00UTC ",
url: "/cont.html ",
userid: "12345"
},
{
timestamp: "2019-03-01 10:30:00UTC",
url: "/ho.html ",
userid: "12347"
}
];
console.log("data", data);
console.log("ex: first data object:", data[0]);
//loop through and grab the timestamp in each object and remove the UTC stamp
const GrabTimeStamp = () => {
data.forEach(function (objects, index) {
const timeStamp = objects.timestamp;
const newTimeStamp = timeStamp.slice(0, 19);
console.log("newTimeStamp:", newTimeStamp, index);
//next step to replace the old timestamp with newTimeStamp
});
};
GrabTimeStamp()
解决方案
您的代码看起来不错,只需重构该片段(使用的最佳方法forEach
):
data.forEach((item, index) => {
const timeStamp = item.timestamp;
const newTimeStamp = timeStamp.slice(0, 19);
item.timestamp = newTimeStamp;
});
它应该可以工作。
推荐阅读
- c++ - Qt Designer 在我的 QMainWindow 中的小部件之间添加拆分器
- java - 如何在 Android 上使用 FFMPeg 库合并两个视频
- python-3.x - 如何从 Python 线性模型中的模型摘要中获取拦截?
- perl - 如何将全局变量的内容保存到 Perl 中的词法变量并从 sub 访问它
- javascript - 根据索引决定类变量名
- javascript - 我可以使用插值字符串解构项目吗?
- python - 如何使用函数调用在 Python 中循环 INPUT 语句
- android - 将一些数据传递给Activity后,如何从同一个Fragment中结束一个Fragment?
- spring-boot - 配置客户端的自动刷新在 Spring Boot 2 中不起作用
- java - For 循环 - 打印操作数除以二