如何使用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
ireaches the last index,data[i+1]isundefined, which would cause a runtime error. - You were assigning
data.is_latest(a property on the array itself) instead ofdata[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
相关产品推荐
相关产品推荐

