António Regadas
António Regadas

Reputation: 724

AngularJS How to group/organize items in object in order to show them in the view

I have a URL with some parameters like this one: http://localhost:9000/#/checkout/?title1=Sodadrink&quantity1=2&price1=129.95&title2=PolaryteGlasses&quantity2=1&price2=59.95#%2F

and I'm getting them with $location.search(), which returns them just fine in an Object like:

Object
   price1: "129.95"
   price2: "59.95"
   quantity1: "2"
   quantity2: "1"
   title1: "Sodastream"
   title2: "Polaryte – Óculos de Sol"
  __proto__: Object

This is cool, but now I need to group each item like:

[item]
   title : Sodastream
   price : 129.95
   quantity : 1
[item]
   title : ---
   price : ---
   quantity : ---

I'm stuck in this part, I've though of counting the total items inside the object, 6, and them group them in groups of 3 by creating a new Object, but didn't work out. Can you help me? Thanks.

Upvotes: 0

Views: 59

Answers (2)

Chukwuemeka Onyenezido
Chukwuemeka Onyenezido

Reputation: 349

Since the number of items in the URL may vary, it is best to not hardcode any number. For this, I am also assuming that every item has 3 properties - title, price and quantity.

Try this:

var numOfItems = Object.keys(input).length/3; // for example, 6 properties will mean 2 items
var output = [];
for (var i = 1; i <= numOfItems; i++) {
  if (input["title"+i]) {
    output.push({title: input["title"+i], price: input["price"+i],quantity: input["quantity"+i]})
  }
}

The output array should contain the objects in the exact way you specified.

Upvotes: 1

Mikkel
Mikkel

Reputation: 7777

You will have to write a bit of javascript to do that.

Assuming that your object from above is called inputs

const MAX_ITEMS=9;
var outputs = [];
for (var i=1,i<MAX_ITEMS;i++) {
    if (inputs["item"+i]) {
        outputs.push({item: inputs["item"+i], price: inputs["price"+i],quantity: inputs["quantity"+i]})
    }
}

Your data will be in the outputs variable

Upvotes: 1

Related Questions