【问题标题】:How to filter a new object depending of Creation Date?如何根据创建日期过滤新对象?
【发布时间】:2020-08-19 16:09:18
【问题描述】:

我有以下对象:

[
    { 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 过滤和映射它,但我不清楚它的逻辑。

任何帮助将不胜感激。

提前致谢!

【问题讨论】:

  • 到目前为止你有没有尝试过?

标签: javascript arrays reactjs object iteration


【解决方案1】:

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

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
}))

【讨论】:

    【解决方案2】:

    这可以通过基本的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);

    【讨论】:

      猜你喜欢
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 2016-06-05
      • 2018-09-27
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      相关资源
      最近更新 更多