In this scenario, given the array provided, I am trying to achieve the desired output by modifying the reduce function. While attempting to assign [cur] to a plans key, I noticed that it is only extracting the first element. I suspect the issue lies in the way I am concatenating the objects, but I am unable to solve it on my own.
{
employee: 'employee_1',
customer: {
name: 'customer_1',
},
startdate: '2020-03-01T23:00:00.000Z'
}, {
employee: 'employee_2',
customer: {
name: 'customer_1',
},
startdate: '2020-03-01T23:00:00.000Z'
}, {
employee: 'employee_3',
customer: {
name: 'customer_1',
},
startdate: '2020-03-01T23:00:00.000Z'
}
plans.reduce(function(o, cur) {
// Get the index of the key-value pair.
var occurs = o.reduce(function(n, item, i) {
return (item.customer.toString() === cur.customer.toString()) ? i : n;
}, -1);
// If the name is found,
if (occurs >= 0) {
// append the current value to its list of values.
o[occurs].employee = o[occurs].employee.concat(cur.employee)
o[occurs].startdate = o[occurs].startdate.concat(cur.startdate)
// Otherwise
} else {
// add the current item to o (but make sure the value is an array).
var obj = {
customer: cur.customer,
employee: [cur.employee],
startdate: [cur.startdate]
};
o = o.concat([obj]);
}
return o;
}, [])
This function reduces the given array to something like this:
{
customer: {
name: 'customer_1'
},
employee: [{
employee: 'employee_1'
}, {
employee: 'employee_2'
}, {
employee: 'employee_3'
}],
startdate: [{
startdate: '2020-03-01T23:00:00.000Z'
}, {
startdate: '2020-03-01T23:00:00.000Z'
}, {
startdate: '2020-03-01T23:00:00.000Z'
}]
}
However, the desired output should look like this:
{
customer: {customer_data},
plans: [{
employee: 'employee_1',
startdate: '2020-03-01T23:00:00.000Z'
}, {
employee: 'employee_2',
startdate: '2020-03-01T23:00:00.000Z'
}, {
employee: 'employee_3',
startdate: '2020-03-01T23:00:00.000Z'
}]
}