我有两个对象
Client = [id, name]
Order = [id, clientId]
我有一个订单数组,并想在一个垫子表中显示它们。我已启动并运行所有内容(因此显示ID和ClientID),但是如何将“订单”中的ClientID与我的客户结合起来才能显示真实姓名?
我什么都找不到。可能没有在Google上搜索正确的内容,也无法针对该简单任务提出一个建议!
最好的问候!
答案 0 :(得分:0)
您可以仅按clientId将订单分组,然后将每个客户端的结果订单数组添加到客户端对象:
const clients = [
{ id: 1, name: "first" },
{ id: 2, name: "second" }
];
const orders = [
{ id: 1, clientId: 1, text: "First Order" },
{ id: 2, clientId: 2, text: "Second Order" },
{ id: 3, clientId: 1, text: "Third Order" }
];
const groupedOrders = {};
orders.forEach(order => {
if (!groupedOrders[order.clientId]) {
groupedOrders[order.clientId] = [];
}
groupedOrders[order.clientId].push(order);
});
const groupedClientsAndOrders = clients.map(client => {
return Object.assign({}, client, { orders: groupedOrders[client.id] || [] });
});
这将产生一个新的数组,如下所示:
[
{
"id": 1,
"name": "first",
"orders": [
{
"id": 1,
"clientId": 1,
"text": "First Order"
},
{
"id": 3,
"clientId": 1,
"text": "Third Order"
}
]
},
{
"id": 2,
"name": "second",
"orders": [
{
"id": 2,
"clientId": 2,
"text": "Second Order"
}
]
}
]
如果您需要每个订单的客户,还可以执行以下操作:
const clients = [
{ id: 1, name: "first" },
{ id: 2, name: "second" }
];
const orders = [
{ id: 1, clientId: 1, text: "First Order" },
{ id: 2, clientId: 2, text: "Second Order" },
{ id: 3, clientId: 1, text: "Third Order" }
];
const joinedOrders = orders.map(order => {
const client = clients.filter(c => c.id == order.id)[0];
return Object.assign({}, order, { client: client });
});