so assume i have 2 arrays of objects...

let orders = [
   { id: 1, itemName: 'Peaches', amount: 2 },
   { id: 2, itemName: 'Mangoes', amount: 1 },
   { id: 3, itemName: 'Mangoes', amount: 10 }
  ];
let items = [
   { id: 1, name: 'Peaches', qty: 10 },
   { id: 2, name: 'Mangoes', qty: 3 }
  ];

and i want to find the list of orders for every item and put them in an array called linkedOrders, I tried the below code:

let linkedOrders = _.map(items, item => _.where(orders, { name: item.name }));
console.log(linkedOrders);

This is what I am getting:

    [{ id: 1, itemName: 'Peaches', amount: 2 }],
    [{ id: 2, itemName: 'Mangoes', amount: 1 },
    { id: 3, itemName: 'Mangoes', amount: 10 }]

but I want something like this:

    [{'Peaches': [
       { id: 1, itemName: 'Peaches', amount: 2 }
     ],
     'Mangoes': [
       { id: 2, itemName: 'Mangoes', amount: 1 },
       { id: 3, itemName: 'Mangoes', amount: 10 }
    ]],

Any help would be appreciated thanks.

1 Answers

0
Programmer On

You can simply do that using Array reduce method.

const result = items.reduce((result, item) => {
    result.push({
        [item.name]: orders.filter((order) => order.itemName === item.name)
    });
    return result;
}, []);

For more information on reduce, check Array​.prototype​.reduce()