Javascript 用于展平对象的Lodash flatMap
我的目标如下:Javascript 用于展平对象的Lodash flatMap,javascript,arrays,object,lodash,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": "34
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"
}
}];
我试图从AllocationInterval.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个元素;一个用于allocationinterval
,另一个用于allocationinterval.jobstaskTimeAllocationInterval
。每个项目本身都有相同的employeeId
和taskId
创建一个函数,该函数将返回给定项和分配的输出项:
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)
]);
你能修正你的数据结构,把括号放在数组周围吗?有点不清楚是
allocationinterval
还是jobTaskTimeAllocationInterval
是数组。对不起我已经用方括号更新了原始版本。这就是数组从API返回的方式。