简体   繁体   中英

Javascript key array by object and aggregate duplicates

I retrieve a list of an order object that comes back as array [Orders], this list can be of any size. Each order object is structured as follows. I am trying to extract the customer from the order as essentially a key and group the orders by each customer.

order: {
 details: {
   price: ""
 }
 customer: {
   name: "blah blah"
   email: "blah@gmail.com"
 }
} 

I need to figure out what the best way to group every order to a specific customer. Ensuring that if multiple orders come back for the same customer they are it ignores duplicates and still adds the orders to an array belonging to each customer. The ideal output would be

customer: {
  name: "Blah Blah",
  email: "blah@gmail.com",
  orders: [Orders]
}

This probably could be found by searching around stack overflow for how to group an array of items, and is probably duplicated...

But, something like this should work for you, assuming that you want to group customers by email.

var result = orders.reduce(customers, order => {
    // comparing customers by email
    var customer = customers.find(c => c.email === order.customer.email);

    if (!customer) {
        customer = {
            name: order.customer.name,
            email: order.customer.email,
            orders: [ order ]
        };
        // or use spread syntax, if you have that available
        // customer = { ...order.customer, orders: [ order ] }
        customers.push(customer);
    } else {
        customer.orders.push(order);
    }
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM