问题描述
我正在尝试从 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 = () => {
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;
};
到目前为止,我只能获取数组中的最后一个营养素。我的营养列表被覆盖,我不知道为什么。我将不胜感激。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)