首页 > 解决方案 > 我想替换数组中对象的值?

问题描述

我的数组中有一个时间戳,我从中删除了 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()

标签: javascriptarraysobjectreplacearray.prototype.map

解决方案


您的代码看起来不错,只需重构该片段(使用的最佳方法forEach):

data.forEach((item, index) => {
   const timeStamp = item.timestamp;
   const newTimeStamp = timeStamp.slice(0, 19);
   item.timestamp = newTimeStamp; 
});

它应该可以工作。


推荐阅读