javascript - 有没有办法停止覆盖对象值?
问题描述
我正在尝试从 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 获取的数组的最后一个元素。关于我可能出错的地方有什么建议吗?
解决方案
您是否尝试过使用 Object.writable 属性:
const obj = {};
Object.defineProperty(obj, 'prop', {
value: 'test',
writable: false
});
console.log(obj.prop);
obj.prop = "test 2";
console.log(obj.prop);
推荐阅读
- database - 在 vb.net 上清除并刷新 DataGridView
- r - R:仅当变量名称包含某个字符串时,才替换 ONE 特定行中的特定值
- silverstripe - Silver stipe 4.5 在管理员创建页面中添加 css
- python - 从 python 调用 Oracle 过程并将变量分配给 python lisr
- c# - 更改数组的索引
- sql-server - “不必要的表扫描”到底是什么意思
- windows - Spark 不再在 Windows 中运行
- r - 合并两个列不均匀的表并保留两个值
- php - 多语言网站数据库中的用户字幕、ID
- regex - 正则表达式匹配中间不在列表中?