Search code examples
javascriptarraysobjectlodash

Lodash flatMap to flatten object


I have the following object:

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"
}
}];

I am trying to pull out all of the start and end times from allocationIntervals.jobTaskTimeAllocationInterval to create something like the following:

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"   
}];

I'm looking at doing this with Lodash flatMap, with something like the following function:

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

Does anyone know of a way to solve the above?


Solution

  • It looks like for every item in arr you need 2 elements in the output array; one for allocationIntervals and one for allocationIntervals.jobTaskTimeAllocationInterval. Each one has the same employeeId and taskId from the item itself.

    Create a function that will return an output item given an item and an allocation:

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

    Call this function twice for each item passing the allocationIntervals for the first call and allocationIntervals.jobTaskTimeAllocationInterval for the second call:

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