如何根据创建日期过滤新对象?

问题描述

我有以下对象:

[
    { createdAt: "08-08-2020,12:04:19 am",id: "1" },{ createdAt: "08-08-2020,id: "2" },{ createdAt: "08-10-2020,id: "3" },id: "4" },{ createdAt: "08-12-2020,id: "5" },{ createdAt: "08-20-2020,id: "6" }
]

如您所见,每个数组都有一个创建日期和一个特定值。我想在这里创建一个看起来像这样的新对象:

[
    { createdAt: "08-08-2020",ids: ["1","2"] },{ createdAt: "08-10-2020",ids: ["3","4"] },{ createdAt: "08-12-2020",ids: ["5"] },{ createdAt: "08-20-2020",ids: ["6" ]}
]

基本上按照创建日期排列ID。我一直在尝试使用ECMA6对此进行过滤和映射,但是对我来说逻辑尚不清楚。

任何帮助将不胜感激。

谢谢!

解决方法

首先,在createdAt和id之间创建一个映射

const array = [
    { createdAt: "08-08-2020,12:04:19 am",id: "1" },{ createdAt: "08-08-2020,id: "2" },{ createdAt: "08-10-2020,id: "3" },id: "4" },{ createdAt: "08-12-2020,id: "5" },{ createdAt: "08-20-2020,id: "6" }
]

const map = {}

array.forEach(item => {
  if (map[item.createdAt] === undefined) {
    map[item.createdAt] = []
  }

  map[item.createdAt].push(item.id)
})

然后,将地图重新​​排列为数组:

const resultingArray = Object.entries(map).map(([createdAt,ids]) => ({
  createdAt,ids
}))
,

这可以通过基本的reduce操作来完成,该操作使用对象将具有相同日期的元素分组。

const arr = [
    { createdAt: "08-08-2020,id: "6" }
];
const res = Object.values(
  arr.reduce((acc,{createdAt,id})=>{
    const date = createdAt.split(",")[0];
    acc[date] = acc[date] || {createdAt: date,ids: []};
    acc[date].ids.push(id);
    return acc;
  },{})
);
console.log(res);