打字稿:从具有条件的对象中获取随机条目并将它们添加到新对象

Typescript: get random entries from object with conditions and add them to a new object

我目前正在研究 Ionic2Typescript

我有一个对象,其中包含一些膳食、卡路里计数和膳食类型(素食等)。

这个对象看起来像这样:

[
   {
      "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"
      ]
   }
]

现在我想生成一个随机膳食计划。

我想添加 3 顿 400 卡路里的随机餐和 2 顿 200 卡路里的零食。

是否有可能通过卡路里值随机 "select" 膳食?

当然有可能。请看一下this plunker。这只是一个小演示,但您可以使用它来获取任意数量的食物。

代码几乎不言自明:

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];
  }

}

请注意,所有魔法都是通过 filter(...)Math.random() 方法实现的。