简体   繁体   English

JS:按今天、昨天、过去 7 天和月份对时间相关对象数组进行分组

[英]JS: Group array of time related objects by today, yesterday, last 7 days, and months

I have the following case.我有以下情况。 Assuming I have an array like this:假设我有一个这样的数组:

const listOfObjects = [
  {
    title: "Title",
    date: "timestamp from today"
  },
  {
    title: "Title",
    date: "timestamp from yesterday"
  },
  {
    title: "Title",
    date: "timestamp from yesterday"
  },
  {
    title: "Title",
    date: "timestamp from one day in the last seven days"
  },
  {
    title: "Title",
    date: "timestamp from last month"
  },
  ...
]

My goal is to group these items in the following structure:我的目标是按照以下结构对这些项目进行分组:

const structeredObjects = {
  "Today": [{
    title: "Title",
    date: "timestamp from today"
  }],
  "Yesterday": [{
    title: "Title",
    date: "timestamp from yesterday"
  },
  {
    title: "Title",
    date: "timestamp from yesterday"
  }],
  "Last seven days": [{
    title: "Title",
    date: "timestamp from one day in the last seven days"
  }],
  "January 2023": [{
    title: "Title",
    date: "timestamp"
  }],
  "December 2022": [{
    title: "Title",
    date: "timestamp"
  }],
  "November 2022": [{
    title: "Title",
    date: "timestamp"
  }],
  ...
}

I guess I can achieve this using Lodash's groupBy .我想我可以使用 Lodash 的groupBy来实现这一点。

Grouping these items by month and year (like "January 2023", "December 2022", etc.) is working.按月份和年份(如“2023 年 1 月”、“2022 年 12 月”等)对这些项目进行分组是可行的。 But how should I go ahead when I want to have the extra keys "Today, Yesterday, Last seven days".但是当我想要额外的键“今天,昨天,最后七天”时,我应该如何提前go。

Thank you very much!非常感谢你!

Something like this might work if your timestamp is the Date object converted to string (you might need to adjust it's date format because timestamps tend to have different format. It's done inside the groupBy method where you check strings for equality)如果您的时间戳是 Date object 转换为字符串,这样的事情可能会起作用(您可能需要调整它的日期格式,因为时间戳往往具有不同的格式。它在 groupBy 方法中完成,您可以在其中检查字符串是否相等)

const listOfObjects = [
  // Your objects here
];

const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const lastSevenDays = new Date(today);
lastSevenDays.setDate(lastSevenDays.getDate() - 7);

const structuredObjects = _.groupBy(listOfObjects, (item) => {
  const itemDate = new Date(item.date);
  if (itemDate.toDateString() === today.toDateString()) {
    return "Today";
  } else if (itemDate.toDateString() === yesterday.toDateString()) {
    return "Yesterday";
  } else if (itemDate > lastSevenDays) {
    return "Last seven days";
  } else {
    return `${itemDate.toLocaleString('default', { month: 'long' })} ${itemDate.getFullYear()}`;
  }
});
console.log(structuredObjects);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM