我在客户变量中有此json:
{
"customers": [
{
"id": 6,
"name": "Joe Bloggs",
"email": "[email protected]",
"supplier_id": 1,
"title": "First Supplier",
"code": "firstsupplier"
},
{
"id": 7,
"name": "Paul",
"email": "[email protected]",
"supplier_id": 1,
"title": "First Supplier",
"code": "firstsupplier"
},
{
"id": 7,
"name": "Paul",
"email": "[email protected]",
"supplier_id": 3,
"title": "New Supplier",
"code": "new"
},
{
"id": 7,
"name": "Paul",
"email": "[email protected]",
"supplier_id": 4,
"title": "PC supplier 3",
"code": "PC03"
},
{
"id": 8,
"name": "John Doe",
"email": "[email protected]",
"supplier_id": 1,
"title": "First Supplier",
"code": "firstsupplier"
}
]
}
我想要更改它,所以它看起来像这样:
{
"customers": [
{
"id": 6,
"name": "Joe Bloggs",
"email": "[email protected]",
"suppliers": [
{
"supplier_id": 1,
"title": "First Supplier",
"code": "firstsupplier"
}
]
},
{
"id": 7,
"name": "Paul",
"email": "[email protected]",
"suppliers": [
{
"supplier_id": 1,
"title": "First Supplier",
"code": "firstsupplier"
},
{
"supplier_id": 3,
"title": "New Supplier",
"code": "new"
},
{
"supplier_id": 4,
"title": "PC supplier 3",
"code": "PC03"
}
]
},
{
"id": 8,
"name": "John Doe",
"email": "[email protected]",
"suppliers": [
{
"supplier_id": 1,
"title": "First Supplier",
"code": "firstsupplier"
}
]
}
]
}
我设法让其中的一部分可以单独工作,但无法在单个函数中全部工作。
例如。我可以创建
suppliers
数组,但是对于客户ID为7的情况,该数组中只有一个供应商。let customers = await query.offset(offset).limit(limit);
customers = customers.reduce((accumulator, item) => {
if (accumulator[item.id]) {
const group = accumulator[item.id];
group.suppliers = [];
group.suppliers.push({
id: item.supplier_id,
code: item.code,
title: item.title
});
} else {
accumulator[item.id] = item;
accumulator[item.id].suppliers = [];
accumulator[item.id].suppliers.push({
id: item.supplier_id,
code: item.code,
title: item.title
});
delete accumulator[item.id].supplier_id;
delete accumulator[item.id].code;
delete accumulator[item.id].title;
}
return accumulator;
}, {});
我所拥有的也看起来很麻烦。如何在更清洁的功能中获得所需的结果?
最佳答案
每次累加器包含一个具有与初始数组中相同的ID的元素时,您只是在重置suppliers
属性。正确的代码是:
let customers = await query.offset(offset).limit(limit);
customers = customers.reduce((accumulator, item) => {
if (accumulator[item.id]) {
const group = accumulator[item.id];
//group.suppliers = [];
group.suppliers.push({
id: item.supplier_id,
code: item.code,
title: item.title
});
} else {
accumulator[item.id] = item;
accumulator[item.id].suppliers = [];
accumulator[item.id].suppliers.push({
id: item.supplier_id,
code: item.code,
title: item.title
});
delete accumulator[item.id].supplier_id;
delete accumulator[item.id].code;
delete accumulator[item.id].title;
}
return accumulator;
}, {});