angular - Typescript: získať náhodné položky z objektu podľa podmienok a pridať ich do nového objektu


Momentálne si trochu skúšam Ionic2 a Typescript.

Mám objekt s niekoľkými jedlami, obsahom kalórií a typom jedla (vegánske a podobne).

Tento objekt vyzerá takto:

[
   {
      "id":14093,
      "name":"Proteinshake mit Wasser – ESN Designer Whey Protein",
      "description":"",
      "thumbnail":null,
      "image":null,
      "calories":[
         "200"
      ],
      "type":[
         "snack"
      ],
      "nutrition":[
         "pescetarier",
         "standart",
         "vegetarisch"
      ]
   },
   {
      "id":14088,
      "name":"Omelette mit Garnelen",
      "description":"",
      "thumbnail":null,
      "image":null,
      "calories":[
         "400"
      ],
      "type":[
         "fruehstueck",
         "gericht"
      ],
      "nutrition":[
         "pescetarier",
         "standart",
         "vegetarisch"
      ]
   }
]

Teraz chcem vytvoriť náhodný jedálniček.

Chcem pridať 3 náhodné jedlá s 400 kalóriami a 2 snacky s 200 kalóriami.

Je nejako možné „vyberať“ jedlá náhodne podľa kalorickej hodnoty?

Odpoveď č. 1

Samozrejme, že je to možné. Prosím, pozrite si tento plunker. Je to len malá ukážka, ale môžete ju použiť na získanie toľkých jedál, koľko chcete.

Kód je pomerne samovysvetľujúci:

import { Component } from "@angular/core";

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  // Your array of meals
  private mealLists: Array<any> = [{...}, {...}, ...]; 

  // The array that's going to store the random meals
  private mealsPlan: Array<any> = [];

  constructor() { }

  // Creates a plan with *mealCount* meals with *calories* calories 
  public getMealPlan(mealCount: number, calories: number) {

    // Reset the data
    this.mealsPlan = [];

    for(let i=0; i<mealCount; i++) {
      // Get all the meals with 200 calories
      let selectedMeals = this.getMealsWithCertainCalories(calories);

      // Get a random meal from that list of meals
      let randomMeal = this.getRandomMeal(selectedMeals);

      // Add that meal to the plan
      this.mealsPlan.push(randomMeal);
    }
  }

  // Select all the meals with *calories* calories
  private getMealsWithCertainCalories(calories: number) {
    return this.mealLists
      .filter(function(aMeal){
        if(parseInt(aMeal.calories[0]) == calories) {
          return true;
        } else {
          return false;
        }
      });
  }

  // Get random index between 0 and the amount of meal sent as parameter
  private getRandomMeal(selectedMeals) {
    let randomIndex = Math.floor((Math.random() * selectedMeals.length) );
    return selectedMeals[randomIndex];
  }

}

Všimnite si, že všetka mágia sa deje pomocou metód filter(...) a Math.random().