I have two arrays of objects periods and people. periods refers to the different periods of time that an organization went through. people refers to the people that were part of that organization. In the result, I want to attach each individual person to the period when they were part of the organization. To do that I am planing to do two different transformations. A sample of the data follows:
DATA
periods = [
{ start_date: "2017-01-01", end_date: "2017-12-01", period: 1 },
{ start_date: "2018-01-01", end_date: "2018-12-01", period: 2 },
{ start_date: "2019-01-01", end_date: "2019-12-01", period: 3 }
]
people = [
{ name: "Paul",
start_date_org: "2017-01-01",
end_date_org: "2018-04-01" },
{ name: "Terence",
start_date_org: "2018-06-01",
end_date_org: "2019-12-01" },
{ name: "Kylian",
start_date_org: "2017-06-01",
end_date_org: "2019-12-01" }
]
How can I combine/merge these two files to get the following transformations?
1st transformation: Attach each individual person to the period/s when they were part of the organization. If possible, add years only as a reference.
result1 = [
{
name: "Paul",
start_date_org: "2017-01-01",
end_date_org: "2018-06-01",
periods: [1, 2],
year: [2017, 2018]
},
{
name: "Terence",
start_date_org: "2018-06-01",
end_date_org: "2019-12-01",
periods: [2, 3],
year: [2018, 2019]
},
{
name: "Kylian",
start_date_org: "2017-06-01",
end_date_org: "2019-12-01",
periods: [1, 2, 3],
year: [2017, 2018, 2019]
}
]
2nd transformation: Expand the result. One object per person and period.
result2 = [
{
name: "Paul",
start_date_org: "2017-01-01",
end_date_org: "2018-06-01",
period: 1,
year: 2017
},
{
name: "Paul",
start_date_org: "2017-01-01",
end_date_org: "2018-06-01",
period: 2,
year: 2018
},
{
name: "Terence",
start_date_org: "2018-06-01",
end_date_org: "2019-12-01",
period: 2,
year: 2018
},
{
name: "Terence",
start_date_org: "2018-06-01",
end_date_org: "2019-12-01",
period: 3,
year: 2019
},
{
name: "Kylian",
start_date_org: "2017-06-01",
end_date_org: "2019-12-01",
period: 1,
year: 2017
},
{
name: "Kylian",
start_date_org: "2017-06-01",
end_date_org: "2019-12-01",
period: 2,
year: 2018
},
{
name: "Kylian",
start_date_org: "2017-06-01",
end_date_org: "2019-12-01",
period: 3,
year: 2019
}
]
My best attempt so far using an if statement for the first transformation follows:
parseTime = d3.timeParse("%Y-%m-%d")
people.map((d, i) => {
periods.map((x, i) => {
if (
parseTime(x.start_date_org) >= parseTime(d.start_date) &&
parseTime(x.start_date_org) <= parseTime(d.end_date)
) {
d.period = x.period;
}
});
return d;
})
Any advice is welcome!