简体   繁体   English

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 },
]

I need to calculate the calories by multiplying carbs, protein, and fat together and then add the results together.我需要通过将碳水化合物、蛋白质和脂肪相乘来计算卡路里,然后将结果加在一起。

Im pretty stuck on this one, i've gotten to我很坚持这个,我已经到了

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

but not really sure where to go from there.但不确定从那里到 go 的位置。

For each food item, get its three values and save the calculation, if I remember it correctly:), in a new property calories :对于每种食物,如果我没记错的话,获取它的三个值并保存计算:),在一个新的属性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
})

That's it.而已。 I hope it's understandable enough.我希望它是可以理解的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM