Lodash flatMap用于展平对象

时间:2017-11-07 18:39:47

标签: javascript arrays object lodash

我有以下对象:

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

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

1 个答案:

答案 0 :(得分:3)

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