【问题标题】:Mapping Array Of Objects By Key按键映射对象数组
【发布时间】:2020-11-26 12:53:31
【问题描述】:

我有两个数组是从一个 reduce 方法创建的,该方法在两个现有数组中搜索日期。然后它将这些日期转换为唯一的对象键。

第一组是名称列表,第二组是一系列指令。

目标是将通过查找相似对象键并添加匹配列表对象而形成的两个数组结合起来,并将其插入到具有对象键列表的指令集中。

首先,它创建了一个如下所示的数组:

const listObj = [
  {11/20/2020: [{name:'Joe', date:11/20/2020}]},
  {11/26/2020 : [{name:'John', date:11/26/2020}]}
]

还有这个:

const scheduleObj = [
  {11/20/2020: {type:'Federal', date:11/20/2020}},
  {11/26/2020 : {type:'State', date:11/26/2020}}
]

我需要的最终产品看起来像:

const scheduleObj = [
  {11/26/2020 : {
    type: 'State',
    list: [{name:'John', date:11/26/2020}]
  },
  ...
]

其中列表是添加的键,数组是与对象键关联的数组

我使用了一个看起来像 lodash 的凌乱方法来让它工作,但我认为必须有某种映射我可以做。

任何帮助将不胜感激

【问题讨论】:

  • 请向我们展示有效的输入和预期的输出。

标签: javascript arrays lodash


【解决方案1】:

这可能有点混乱,也不是故障证明,具体取决于您在 listObjscheduleObj 中的内容。例如。 scheduleObj 中的重复日期可能会导致使用此方法出现问题,如果日期在两个列表中都不是唯一的,您可能必须使用另一个 key

scheduleObj.map((s) => {
  // get the first key of the object as the date you're going to group with
  const date = Object.keys(s)[0];

  // filter the object that matches the date
  const listObjFilter = listObj.filter((o) => Object.keys(o)[0] === date);

  // get the list for the given date (or empty array if nothing found)
  const listForDate = listObjFilter.length ? listObjFilter[0][date] : [];

  // build the result object
  return {
    [date]: {
      type: s[date]['type'],
      list: listForDate
    }
  };
})

请注意,我一直认为您在listObjscheduleObj 的列表内的对象中只有一个键。

【讨论】:

  • 日期应该是唯一的,因为它是减少的!当我把它转录出来时会通知你的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-28
  • 2021-09-10
  • 2012-05-30
  • 1970-01-01
  • 2016-09-21
  • 2017-08-25
  • 2018-11-19
相关资源
最近更新 更多