Is there a way to stop overwriting Object values?

191 Views Asked by At

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?

2

There are 2 best solutions below

0
Brandon McConnell On

Have you tried using the Object.writable property:

const obj = {};
Object.defineProperty(obj, 'prop', {
    value: 'test',
    writable: false
});

console.log(obj.prop);

obj.prop = "test 2";

console.log(obj.prop);

0
Goutham On

You can test the below.

const foodData = [
  {
    amount: 1000,
    nutrient: {
      id: 1001, number: "201", name: "One lipid (fat)", rank: 100, unitName: "g"
    }
  },
   {
    amount: 7000,
    nutrient: {
      id: 1001, number: "201", name: "One lipid (fat)", rank: 100, unitName: "g"
    }
  },
  {
    amount: 2000,
    nutrient: {
      id: 1002, number: "202", name: "Two lipid (fat)", rank: 200, unitName: "g"
    }
  },
  {
    amount: 3000,
    nutrient: {
      id: 1003, number: "203", name: "Three lipid (fat)", rank: 300, unitName: "g"
    }
  },
  {
    amount: 4000,
    nutrient: {
      id: 1004, number: "204", name: "Four lipid (fat)", rank: 400, unitName: "g"
    }
  }
];

const mappedData = foodData.reduce((acc, cur) => {
  if (acc[cur.nutrient.name]) {
    return {
      ...acc,
      [cur.nutrient.name]: {
        name: cur.nutrient.name,
        amount: acc[cur.nutrient.name].amount +  cur.amount,
        unitName:  cur.nutrient.unitName
      },

    }
  } else {
    return {
      ...acc,
      [cur.nutrient.name]: {
        name: cur.nutrient.name,
        amount: cur.amount,
        unitName: cur.nutrient.unitName
      },
    }
  }
}, {});

console.log('mappedData', mappedData);

Expected Output: {
  "One lipid (fat)": {
    "name": "One lipid (fat)",
    "amount": 8000,
    "unitName": "g"
  },
  "Two lipid (fat)": {
    "name": "Two lipid (fat)",
    "amount": 2000,
    "unitName": "g"
  },
  "Three lipid (fat)": {
    "name": "Three lipid (fat)",
    "amount": 3000,
    "unitName": "g"
  },
  "Four lipid (fat)": {
    "name": "Four lipid (fat)",
    "amount": 4000,
    "unitName": "g"
  }
}