简体   繁体   中英

Typescript: Array of Objects of another Array (Angular6)

I have this array of "food":

"food": [
 { 
    "id": 11,
    "name": "Kabeljaufilet",
    "preis": 3.55,
    "art": "mit Fisch"
},
{
  "id": 12,
  "name": "Spaghetti Bolognese",
  "preis": 3.85,
  "art": "mit Fleisch"
},
{
  "id": 13,
  "name": "Pizza Salami",
  "preis": 3.99,
  "art": "mit Fleisch"
},

Now I need another Array called "foodplan", where I can add, delete etc. foods from the first array.

I have never created Arrays where Objects of another Arrays were implemented. How to go on now?

Foodplan needs the Attributes: FoodPerWeek , where 5 food objects are in and WeekNumber Foodplan needs methods to showFood, addFood, changeFood and deleteFood.

This is just a basic example. Of course you could dynamically resize the array if you prefer. There need to be some checks to validate the input, etc. I leave this to you. Have fun.

enum WeekDay {
  Monday = 0,
  Tuesday = 1,
  Wednesday = 2,
  Thursday = 3,
  Friday = 4
}

class Food {
  public id: number
  public name: string
  public preis: number
  public art: string
}

class FoodPlan {
  private weeklyFood: Food[] = new Array<>(5)

  addFood(food: Food, weekDay: WeekDay) {
    this.weeklyFood[weekDay] = food
  }

  showFood(weekDay: WeekDay) {
    console.log(this.weeklyFood[weekDay])
  }

  remove(weekDay: WeekDay) {
    this.weeklyFood[weekDay] = null
  }
}
let foodPlan: FoodPlan = new FoodPlan()
let firstFood: Food = new Food()

firstFood.id = 1
firstFood.name = "Kabeljaufilet"
firstFood.preis = 3.55
firstFood.art = "mit Fisch"

foodPlan.addFood(firstFood, WeekDay.Wednesday)
foodPlan.showFood(WeekDay.Wednesday)
foodPlan.remove(WeekDay.Wednesday)

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