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

时间:2020-08-19 16:09:18

标签: javascript arrays reactjs object iteration

我有以下对象:

[
    { createdAt: "08-08-2020, 12:04:19 am", id: "1" },
    { createdAt: "08-08-2020, 12:04:19 am", id: "2" },
    { createdAt: "08-10-2020, 12:04:19 am", id: "3" },
    { createdAt: "08-10-2020, 12:04:19 am", id: "4" },
    { createdAt: "08-12-2020, 12:04:19 am", id: "5" },
    { createdAt: "08-20-2020, 12:04:19 am", 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对此进行过滤和映射,但是对我来说逻辑尚不清楚。

任何帮助将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:1)

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

const array = [
    { createdAt: "08-08-2020, 12:04:19 am", id: "1" },
    { createdAt: "08-08-2020, 12:04:19 am", id: "2" },
    { createdAt: "08-10-2020, 12:04:19 am", id: "3" },
    { createdAt: "08-10-2020, 12:04:19 am", id: "4" },
    { createdAt: "08-12-2020, 12:04:19 am", id: "5" },
    { createdAt: "08-20-2020, 12:04:19 am", 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
}))

答案 1 :(得分:0)

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

const arr = [
    { createdAt: "08-08-2020, 12:04:19 am", id: "1" },
    { createdAt: "08-08-2020, 12:04:19 am", id: "2" },
    { createdAt: "08-10-2020, 12:04:19 am", id: "3" },
    { createdAt: "08-10-2020, 12:04:19 am", id: "4" },
    { createdAt: "08-12-2020, 12:04:19 am", id: "5" },
    { createdAt: "08-20-2020, 12:04:19 am", 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);

相关问题