我在客户变量中有这个 json:
{
"customers": [
{
"id": 6,
"name": "Joe Bloggs",
"email": "joe@bloggs.com",
"supplier_id": 1,
"title": "First Supplier",
"code": "firstsupplier"
},
{
"id": 7,
"name": "Paul",
"email": "paul@hotmail.com",
"supplier_id": 1,
"title": "First Supplier",
"code": "firstsupplier"
},
{
"id": 7,
"name": "Paul",
"email": "paul@hotmail.com",
"supplier_id": 3,
"title": "New Supplier",
"code": "new"
},
{
"id": 7,
"name": "Paul",
"email": "paul@hotmail.com",
"supplier_id": 4,
"title": "PC supplier 3",
"code": "PC03"
},
{
"id": 8,
"name": "John Doe",
"email": "john@doe.com",
"supplier_id": 1,
"title": "First Supplier",
"code": "firstsupplier"
}
]
}
我想更改它,使其看起来像这样:
{
"customers": [
{
"id": 6,
"name": "Joe Bloggs",
"email": "joe@bloggs.com",
"suppliers": [
{
"supplier_id": 1,
"title": "First Supplier",
"code": "firstsupplier"
}
]
},
{
"id": 7,
"name": "Paul",
"email": "paul@hotmail.com",
"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": "john@doe.com",
"suppliers": [
{
"supplier_id": 1,
"title": "First Supplier",
"code": "firstsupplier"
}
]
}
]
}
我已经设法让其中的一部分单独工作,但我无法让这一切在一个函数中工作。
例如我可以创建 suppliers
数组,但对于客户 ID 7 的情况,数组中仅出现一个 vendor 。
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;
}, {});
我的东西看起来也很麻烦。如何在更清晰的函数中获得我想要的结果?
最佳答案
嗨@runnerpaul,在您的代码中一切都很完美,只需删除行 group.suppliers = [];
它将按照您的期望工作
关于javascript - Node.js应用程序中的reduce函数省略json json数据并且太麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56136336/