mercredi 27 janvier 2016

Combine items in array by their key

I am using Ember Data to get some items for a cart. These items may look something like this

[
  {
    "item_id":"5635",
    "raffle_purchase_id":"1060",
    "item_name":"***",
    "item_desc":"***",
    "item_image":"5635-Ilbt8xNGsD-cropped.png",
    "item_amt":"2",
    "item_type":"raffle"
  },
  {
    "item_id":"5635",
    "raffle_purchase_id":"1061",
    "item_name":"***",
    "item_desc":"***",
    "item_image":"5635-Ilbt8xNGsD-cropped.png",
    "item_amt":"4",
    "item_type":"raffle"
  },
  {
    "item_id":"5635",
    "raffle_purchase_id":"1563",
    "item_name":"***",
    "item_desc":"***",
    "item_image":"5635-Ilbt8xNGsD-cropped.png",
    "item_amt":"2",
    "item_type":"raffle"
  },
  ...
]

Each item here has a different purchase ID that I need to update on the server side so I need to send back all the items to update back to the server. However when I'm displaying these I don't want to show every line of this same purchase over and over again. Rather I want to combine those and calculate the total those purchases cost.

Each item has an item ID, in this case those are the same for these 3 (and potentially more) items, and there might be a handful of other purchases of the same item multiple times that I want to do the same thing to.

Basically I need to get all the items here that have the same ID, get a total sum of their item_amt property, and then combine them and show just one line item with the total.

I'm a little lost on this one as to where to start and where to do this. Currently this return is coming from the route in the model hook so I know I can do whatever processing I need to before actually setting the model. However I want to make sure I keep the original items intact (as I will need to know the unique raffle_purchase_id's) for later when the user is paying for these.




Aucun commentaire:

Enregistrer un commentaire