我想替换数组中对象的值?

I want to replace the value of an object inside an array?

我的数组中有一个时间戳,我已经从中删除了 UTC 字母,我想用“新”时间戳(没有 UTC)替换旧时间戳 也许有更简单的删除方法?

所以我尝试用 .forEach 和 .map 循环遍历我的数据,试图替换它,但仍然没有弄清楚如何做到这一点。 我看过一堆关于这个的 Whosebug 线程,但还没有找到我开始工作的解决方案....显然遗漏了一些东西或写错了一些东西。

所以谁能指导我如何以最好的方式解决这个问题?

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; 
});

它应该可以工作。

您知道不能更改用“const”声明的变量吗?所以看起来你想在这里使用“var”。最后3个字母可以用"slice(0, -3)"去掉。

var 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
var grabTimeStamp = () => {
  data.forEach(function (object, index) {
   
    var newTimeStamp = object.timestamp.slice(0, -3);
    console.log("newTimeStamp:", newTimeStamp, index);

    //next step to replace the old timestamp with newTimeStamp
    object.timestamp = newTimeStamp;
  });
};
grabTimeStamp();

由于您似乎对编码还很陌生,因此我尝试仅更改您代码中的一些内容。但是你的函数 grabTimeStamp 可以做得更短:

function removeTimestamp(data){
    data.foreach((item, index) => {
        item.timestamp = item.timestamp.slice(0, -3);
    });
}
removeTimestamp(data);