我目前正在尝试使用 Ionic2
和 Typescript
。
我有一个对象,其中包含一些膳食、卡路里计数和膳食类型(素食等)。
这个对象看起来像这样:
[
{
"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 卡路里的零食。
是否有可能通过卡路里值随机“选择”膳食?
最佳答案
当然可以。请看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()
方法完成的。
关于angular - typescript :从具有条件的对象中获取随机条目并将它们添加到新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39082509/