[英]Combine arrays to one array
假設我有以下數組,如何通過修改給定的 reduce 函數來實現這個問題中的最后一個給定示例?
我試圖將 [cur] 分配給一個計划鍵,但它只將第一個元素放出。
我覺得這與我連接對象的方式有關,但我無法自己弄清楚。
{
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;
}, [])
這將給定的數組減少到如下所示:
{
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',
startdate: '2020-03-01T23:00:00.000Z'
}, {
employee: 'employee_3',
startdate: '2020-03-01T23:00:00.000Z'
}]
}
我修改了您的解決方案以獲得所需的輸出。
您應該使用 find 方法來檢查數組中是否已經存在 customer ,而不是使用 reduce 。 你也沒有考慮到計划數組,我已經添加了。
var plans = [ { 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' } ]; 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.