我正在尝试从 USDA API 中提取“能源”,如下面的控制台日志所示。
0: {nutrient: {…}, type: "FoodNutrient"}
1: {type: "FoodNutrient", nutrient: {…}, foodNutrientDerivation: {…}, id: 1837207, amount: 87.58, …}
2:
amount: 39
dataPoints: 0
foodNutrientDerivation: {id: 49, code: "NC", description: "Calculated", foodNutrientSource: {…}}
id: 1837206
nutrient: {id: 1008, number: "208", name: "Energy", rank: 300, unitName: "kcal"}
type: "FoodNutrient"
proto: Object
这是我的 CalculateNutritionInfo 函数:
CalculateNutritionInfo = () => {
let meals = ["Breakfast", "Lunch", "Dinner", "Snacks"];
let { reports } = this.state;
let nutrient = {};
meals.forEach((meal) => {
this.state[meal].forEach((item) => {
nutrient = this.FillNutrients(
nutrient,
reports[item.foodNutrients],
item.servings
);
console.log(reports[item.foodNutrients]);
});
});
console.log(nutrient);
let nutrientList = Object.keys(nutrient).map((item) => nutrient[item]);
console.log(nutrientList);
let empty = nutrientList.length === 0 ? true : false;
this.setState({
calories: empty ? 0 : nutrient["Energy"].amount,
protein: empty ? 0 : nutrient["Protein"].value,
fat: empty ? 0 : nutrient["Total lipid (fat)"].value,
carbs: empty ? 0 : nutrient["Carbohydrate, by difference"].value,
nutrientList,
});
};
这是我的 FetchReports 函数:
FetchReports = () => {
let uri = encodeURI(
`https://api.nal.usda.gov/fdc/v1/foods?api_key=[my_key]${this.state.ndbno_list}`
);
fetch(uri, {
mode: "cors",
})
.then((res) => res.json())
.then((data) => {
let reports = {};
data.forEach((item) => {
reports[item.foodNutrients.nutrient] = item.foodNutrients;
});
this.setState(
{
reports,
},
function () {
this.CalculateNutritionInfo();
}
);
});
};
这是我的 FillNutrients 函数:
FillNutrients = (nutrients, foodNutrients, servings) => {
foodNutrients.forEach((nutrient) => {
let { name, amount, unitName } = nutrient;
servings = parseFloat(servings);
servings = isNaN(servings) ? 0 : servings;
let newValue = Math.round(parseFloat(amount) * servings);
if (nutrients[name]) {
nutrients[name].name = nutrient.nutrient.name;
nutrients[name].amount = nutrient.amount;
nutrients[name].unitName = nutrient.nutrient.unitName;
} else {
nutrients[name] = {
name,
amount: newValue,
unitName,
};
}
});
return nutrients;
};
到目前为止,我只能获得阵列中的最后一种营养。我的 nutritionalList 被覆盖了,我不知道为什么。我将不胜感激任何帮助。