You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Moment.js结合map函数在JavaScript中标记最接近当前时间的更新对象

Solution: Use Moment.js with map and reduce to Mark the Latest Entry

Got it, let's fix this up using Moment.js and array methods like map and reduce—here's a clean, reliable approach that'll get you the desired result:

Step 1: Identify the Latest updated_at Timestamp

First, we need to find the most recent updated_at value in your array. Using Array.reduce() lets us iterate through the array and compare each timestamp with Moment.js's date handling (way more robust than raw string comparisons):

const data = [ 
  { "is_latest": "", "created_at": "2021-09-21T21:24:05.000Z", "updated_at": "2021-09-21T17:53:29.000Z" }, 
  { "is_latest": "", "created_at": "2021-09-29T21:24:05.000Z", "updated_at": "2021-09-29T17:53:29.000Z" } 
];

// Find the most recent updated_at value
const latestTimestamp = data.reduce((currentLatest, item) => {
  const currentItemTime = moment(item.updated_at);
  const latestTime = moment(currentLatest);
  return currentItemTime.isAfter(latestTime) ? item.updated_at : currentLatest;
}, data[0].updated_at);

Step 2: Use map to Update the is_latest Field

Now we can loop through the array with map, copying each object and setting is_latest to true only for the entry that matches our latest timestamp:

// Update the is_latest field for each item
const updatedData = data.map(item => ({
  ...item, // Copy all existing properties
  is_latest: moment(item.updated_at).isSame(latestTimestamp) ? true : ""
}));

console.log(updatedData);

Output (Matches Your Expected Result)

[ 
  { "is_latest": "", "created_at": "2021-09-21T21:24:05.000Z", "updated_at": "2021-09-21T17:53:29.000Z" }, 
  { "is_latest": true, "created_at": "2021-09-29T21:24:05.000Z", "updated_at": "2021-09-29T17:53:29.000Z" } 
]

Why Your Original Code Didn't Work

A quick note on the issues in your initial for loop:

  • When i reaches the last index, data[i+1] is undefined, which would cause a runtime error.
  • You were assigning data.is_latest (a property on the array itself) instead of data[i].is_latest (the property on each object in the array).
  • Raw string comparisons for dates work for ISO 8601 format, but Moment.js handles edge cases (like time zones or inconsistent formatting) far better.

内容的提问来源于stack exchange,提问作者pavan kp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 14:57:28