我有以下对象:

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


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

最佳答案

看起来对于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)
]);

关于javascript - Lodash flatMap展平对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47165218/

10-10 23:04