JavaScript:使用 .forEach 向数组项添加新的 属性

JavaScript: Add new property to array items using .forEach

let foods = [
  { name: 'bread', carbs: 36, protein: 8, fat: 2 },
  { name: 'mayo mustard mix', carbs: 0, protein: 0, fat: 10 },
  { name: 'turkey', carbs: 0, protein: 25, fat: 1 },
  { name: 'cheese', carbs: 0, protein: 5, fat: 7 },
]

我需要通过将碳水化合物、蛋白质和脂肪相乘来计算卡路里,然后将结果相加。

我非常坚持这一点,我已经做到了

foods.forEach((element, index, array => { })

但不确定从那里去哪里。

对于每个食品,获取其三个值并保存计算,如果我没记错的话:),在一个新的 属性 calories:

let foods = [ 
  { name: 'bread', carbs: 36, protein: 8, fat: 2 }, 
  { name: 'mayo mustard mix', carbs: 0, protein: 0, fat: 10 }, 
  { name: 'turkey', carbs: 0, protein: 25, fat: 1 }, 
  { name: 'cheese', carbs: 0, protein: 5, fat: 7 }
];

foods.forEach(food => {
  const { carbs = 0, protein = 0, fat = 0 } = food;
  food.calories = carbs * 4 + protein * 4 + fat * 9;
});

console.log(foods);


function calculate_calories ( food ) { return something }
// this function should calculate the calories from input
// I assume you will do this one yourself

foods.forEach( food => {
  var cal = calculate_calories ( food )
  food.calories = cal
})

就是这样。我希望它足够容易理解。