简体   繁体   中英

Typescript use Map or Object

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?

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 Map s is that you get fast lookup and can use Object s as keys instead of just String s.

 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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM