【问题标题】:Lodash flatMap to flatten objectLodash flatMap 用于展平对象
【发布时间】:2017-11-07 18:39:46
【问题描述】:

我有以下对象:

const arr = [{
 "@id": "6005752",
 employeeId: {
  id: "22826"
},
allocationIntervals: {
 jobTaskTimeAllocationInterval: {
  "@id": "34430743",
   startTime: "2017-03-15T01:50:00.000Z",
   endTime: "2017-03-15T02:50:00.000Z"
 },
   "@id": "34430756",
   startTime: "2017-04-16T02:50:00.000Z",
   endTime: "2017-04-16T03:50:00.000Z"
},
taskId: {
 id: "16465169"
}
}];

我正在尝试从 allocationIntervals.jobTaskTimeAllocationInterval 中提取所有开始和结束时间,以创建类似以下内容:

const arr = [{
  employeeId: "22826",
  taskId: "16465169"
  startTime: "2017-03-15T01:50:00.000Z",
  endTime: "2017-03-15T02:50:00.000Z"
  },
  {
  employeeId: "22826",
  taskId: "16465169",
  startTime: "2017-04-16T02:50:00.000Z",
  endTime: "2017-04-16T03:50:00.000Z"   
}];

我正在考虑使用 Lodash flatMap 执行此操作,其功能类似于以下功能:

const result = _.flatMap(arr, item => {
  return _.map(item.allocationIntervals, allocation => _.defaults({ start: item.jobTaskTimeAllocationInterval.startTime }, allocation));
});

有人知道解决上述问题的方法吗?

【问题讨论】:

  • 您能否更正您拥有的数据结构以在数组周围放置括号?有点不清楚allocationIntervals 还是jobTaskTimeAllocationInterval 是数组。
  • 对不起! - 我已经用方括号包裹原件进行了更新。这就是数组从 API 返回的方式。

标签: javascript arrays object lodash


【解决方案1】:

看起来arr 中的每个项目都需要输出数组中的 2 个元素;一个用于allocationIntervals,一个用于allocationIntervals.jobTaskTimeAllocationInterval。每个项目本身都有相同的employeeIdtaskId

创建一个函数,该函数将在给定项目和分配的情况下返回输出项目:

const createAllocation = (item, allocation) => ({
    employeeId: item.employeeId.id, 
    taskId: item.taskId.id, 
    startTime: allocation.startTime, 
    endTime: allocation.endTime
});

为第一次调用传递allocationIntervals 和第二次调用传递allocationIntervals.jobTaskTimeAllocationInterval 的每个项目调用此函数两次:

const result = _.flatMap(arr, item => [
    createAllocation(item, item.allocationIntervals), 
    createAllocation(item, item.allocationIntervals.jobTaskTimeAllocationInterval)
]);

【讨论】:

    猜你喜欢
    • 2020-09-05
    • 2017-10-19
    • 1970-01-01
    • 2016-06-20
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    相关资源
    最近更新 更多