首页 > 解决方案 > 有没有办法停止覆盖对象值?

问题描述

我正在尝试从 USDA Food Data Central api 中提取信息。具体来说,我想提取“营养”和“数量”下的“名称”。提取的信息显示在此片段中:

输入-报告[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

输出:

{undefined: {…}}
undefined: {name: "Fatty acids, total saturated", amount: 13.33, unit: undefined}
__proto__: Object

我有一个空对象,我将它传递给一个函数,该函数用必要的数据填充该对象。我的下一步是在这个对象上使用 Object.keys() 并映射项目。下面是我试图做到这一点的方法。

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
})

}

我相信我的问题出在 FillNutrients 函数中,因为在映射时,名称返回为未定义,并且只返回一种营养素。这始终是从 api 获取的数组的最后一个元素。关于我可能出错的地方有什么建议吗?

标签: javascriptarraysreactjsjavascript-objectsusda-fooddata-central-api

解决方案


您是否尝试过使用 Object.writable 属性:

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

console.log(obj.prop);

obj.prop = "test 2";

console.log(obj.prop);


推荐阅读