0

I am currently doing a basic Pizza Delivery App. So you click on a Pizza you want and it gets added to a list, which is grouping the results.

So it should display:

Pizza Margarita 2x Pizza Salame 1x

I thought about doing a Map like Map<Pizza, number> where Pizza is my object and the number is the amount.

However this doesnt feel right. Also I can't iterate with ngFor through it.

So wouldn't it just be easy to create an object, like: { "pizza": Pizza, "amount": 2} and put this in an array?

1
  • 1
    "wouldn't it just be easy to create an object" - that sounds pretty easy, so what's your question? Commented Jul 23, 2018 at 15:56

1 Answer 1

2

It's very much up to your use case.

So wouldn't it just be easy to create an object, like: { "pizza": Pizza, "amount": 2} and put this in an array?

You will have to search the Array if you want to get a specific item out of it and you don't know the index.

The benefit of Maps is that you get fast lookup and can use Objects as keys instead of just Strings.

class Pizza {};

// Using Map
const orderMap = new Map();
const margaritaPizza = new Pizza();
const salamePizza = new Pizza();

orderMap.set(margaritaPizza, 2);
orderMap.set(salamePizza, 1);

console.log(`Margarita ammount: ${orderMap.get(margaritaPizza)}`);
console.log(`Salame ammount: ${orderMap.get(salamePizza)}`);

// Using Array
const orderArr = [];

orderArr.push({
  pizza: "margaritaPizza",
  ammount: 2
});

orderArr.push({
  pizza: "salamePizza",
  ammount: 1
});

console.log(`Margarita ammount: ${orderArr.find(el => el.pizza === "margaritaPizza").ammount}`);
console.log(`Salame ammount: ${orderArr.find(el => el.pizza === "salamePizza").ammount}`);


Additionally, you say:

I thought about doing a Map like Map where Pizza is my object and the number is the amount.

However this doesnt feel right. Also I can't iterate with ngFor through it.

Map implements @@iterator and can be converted to a plain Array using Array.from().

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.