我最近开始尝试函数式编程,并且我正在尝试转换我使用命令式编程编写的旧模块。
假设我有两个对象数组,即
orders: [
{
idOrder: 1,
amount: 100,
customerId: 25,
},
{
idOrder: 2,
amount: 200,
customerId: 20,
}
]
customers: [
{
customerId: 20,
name: "John Doe",
orders: []
},
{
customerId: 25,
name: "Mary Jane",
orders: []
}
]
我想将所有订单推送给各自的客户。这样做有干净的方法吗?
我试过这个,但显然它不会这样:
customers.orders = orders.filter((x) => {
if (x.customerId === customerId) {
customer.orders.push(x);
}
});
由于
答案 0 :(得分:2)
您可以使用Map
并先获取所有客户,然后将订单推送给客户。
var object = { orders: [{ idOrder: 1, amount: 100, customerId: 25 }, { idOrder: 2, amount: 200, customerId: 20 }], customers: [{ customerId: 20, name: "John Doe", orders: [] }, { customerId: 25, name: "Mary Jane", orders: [] }] },
map = object.customers.reduce((m, a) => m.set(a.customerId, a), new Map);
object.orders.forEach(a => map.get(a.customerId).orders.push(a));
console.log(object.customers);
答案 1 :(得分:0)
可能的解决方案:
for (c of customers){
c.orders.push(orders.filter( function(o){ return o.customerId === c.customerId} ));
}
答案 2 :(得分:0)
如果您认为customers
为累加器,则Reduce orders
可以customers
作为初始值。
注意:如果您不希望将此作为克隆 customers
的副作用,则会发生变异customers
。还没有找到customerId的错误处理。
var orders = [{ idOrder: 1, amount: 100, customerId: 25 }, { idOrder: 2, amount: 200, customerId: 20}];
var customers = [{ customerId: 20, name: "John Doe", orders: [] }, { customerId: 25, name: "Mary Jane", orders: [] } ];
var customers_orders = orders.reduce(
(accum, v) =>
{ accum.find(
c => c.customerId == v.customerId).orders.push(v);
return accum;
}, customers);
console.log(customers_orders);
答案 3 :(得分:0)
您可以编写一个函数并将其传递给reduce方法并使用map
组合它只有一件事:一旦创建,它可能永远不会改变。您可以使用Object.assign和concat。
var customersWithOrders = customers.map(function(customer) {
var relatedOrders = orders.filter(function(order) { return order.customerId === customer.customerId })
return Object.assign(
customer,
{
orders: customer.orders.concat(relatedOrders)
}
)
})