问题描述
让我说我有以下数组,如何通过修改给定的reduce函数来实现此问题中的最后一个给定示例?
我试图将[cur]分配给一个计划密钥,但是它只将第一个元素放出。
我觉得这与我连接对象的方式有关,但是我无法自行解决。
{
employee: 'employee_1',customer: {
name: 'customer_1',},startdate: '2020-03-01T23:00:00.000Z'
},{
employee: 'employee_2',{
employee: 'employee_3',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;
},[])
这会将给定的数组简化为如下形式:
{
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'
}]
}
但是我需要的是这样的
{
customer: {customer_data},plans: [{
employee: 'employee_1',startdate: '2020-03-01T23:00:00.000Z'
},{
employee: 'employee_2',{
employee: 'employee_3',startdate: '2020-03-01T23:00:00.000Z'
}]
}
解决方法
我修改了您的解决方案,以获得所需的输出。
您应该使用find方法来检查客户是否已存在于数组中,而不是使用reduce方法。 另外,您没有考虑plans数组,我已经添加了。
var plans = [
{
employee: 'employee_1',customer: {
name: 'customer_1',},startdate: '2020-03-01T23:00:00.000Z'
},{
employee: 'employee_2',{
employee: 'employee_3',startdate: '2020-03-01T23:00:00.000Z'
}
];
var result = plans.reduce(function(o,cur) {
// Get the index of the key-value pair.
var occurs = o.find(ob=> ob.customer.name === cur.customer.name);
// If the name is found,if (occurs) {
// append the current value to its list of values.
occurs.plans.push( {employee: cur.employee,startdate: cur.startdate} )
// Otherwise
} else {
// add the current item to o (but make sure the value is an array).
var obj = {
customer: cur.customer,plans:[
{employee: cur.employee,startdate: cur.startdate}
]
};
o = o.concat(obj);
}
return o;
},[])
console.log(result)