1

Lets say I have an array with values

product: [{ 
'product_id': 247
'order_id': 4
}
{ 
'product_id': 245
'order_id': 3
}
{ 
'product_id': 247
'order_id': 3
}]

I have button passing 'product_id' and 'order_id', and every time the button is pressed, I want an object to be something like this, the 'product_id' gets added at the end of the object array accordingly.

[{4: [247, 247, 247], 3: [247, 245, 247]}]

I have tried using different array methods

var productarray = product
  productarray.reduce((order, obj)=> {
    let key = obj['order_id']
      if (!order[key]) {
      order[key] = []
     }
   order[key].push(obj.product_id);
})

but I'm not able to get the result I'm looking for. Sorry if this a vague question. Thank you in advance.

bjacob596
  • 73
  • 8

1 Answers1

0

Seems you need to collapse by key, but you have a few mistakes in your sample, this should work:

var products = [{
    'product_id': 247,
    'order_id': 4
},
{
    'product_id': 245,
    'order_id': 3
},
{
    'product_id': 247,
    'order_id': 3
}];

var orders = products.reduce((m, c) => {
    var order = m[c.order_id];
    if (order) {
        order.push(c.product_id);
    } else {
        m[c.order_id] = [c.product_id];
    }
    return m;
}, {});

console.log(orders);
  • Thank you for answering, but Im still having the same issue I had before, this is same functionality as mentioned above. – bjacob596 Mar 19 '21 at 16:57
  • @bjacob596 can you define inputs/outputs more clearly? – Alex Pereverzyev Mar 19 '21 at 17:50
  • you may try this instead of reduce but guessing is a bad practice :) var clicks = products.map(p => p.product_id); var orders = Array.from(new Set(products.map(p => p.order_id))).map(id => { return { [id]: clicks }}); – Alex Pereverzyev Mar 19 '21 at 17:51