簡體   English   中英

我想替換數組中對象的值?

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

我的數組中有一個時間戳,我已經從中刪除了 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; 
});

它應該工作。

你知道用“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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM