I am trying to pull information from the USDA Food Data Central api. Specifically I would like to pull the "name" found under "nutrient" and the "amount". The information pulled is shown in this snippet:
Input- reports[item.fdcId]
1588171: Array(9)
0:
amount: 93.33
foodNutrientDerivation: {id: 70, code: "LCCS", description: "Calculated from value per serving size
measure", foodNutrientSource: {…}}
id: 20460285
nutrient: {id: 1004, number: "204", name: "Total lipid (fat)", rank: 800, unitName: "g"}
type: "FoodNutrient"
__proto__: Object
Output:
{undefined: {…}}
undefined: {name: "Fatty acids, total saturated", amount: 13.33, unit: undefined}
__proto__: Object
I have an empty object that I pass into a function which fills that object with the necessary data. My next step would be to use Object.keys() on this object and map the items. Below is how I am trying to do that.
FillNutrients = (nutrients, foodNutrients, servings) => {
foodNutrients.forEach(nutrient => {
let {name, amount, unitName} = nutrient;
if(nutrients[name]){
nutrients[name].name = name;
nutrients[name].amount = amount;
nutrients[name].unitName = unitName;
}
else{
nutrients[name] = {
name,
amount,
unitName
}
}
})
return nutrients
}
CalculateNutritionInfo = () => {
let meals = ["Breakfast", "Lunch", "Dinner", "Snacks"]
let {reports} = this.state;
let nutrients = {};
meals.forEach(meal => {
this.state[meal].forEach(item => {
nutrients = this.FillNutrients(nutrients, reports[item.fdcId], item.servings);
})
})
let nutrientList = Object.keys(nutrients).map(item => nutrients[item]);
let empty = nutrientList.length === 0 ? true : false;
this.setState({
calories: empty ? 0: nutrients['Energy'].amount,
protein: empty ? 0: nutrients['Protein'].value,
fat: empty ? 0: nutrients['Total lipid (fat)'].value,
carbs: empty? 0: nutrients['Carbohydrate, by difference'].value,
nutrientList
})
}
I believe that my problem is in the FillNutrients function because when mapping, the name comes back as undefined and there is only ever one nutrient that is returned. This is always the last element of the array fetched from the api. Any suggestions on where I could be going wrong?