[英]Object not mutating
Trying to mutate objects in a for loop. 尝试在for循环中更改对象。
I am expecting console.log(dish)
to log the dish
object with an ingredients
property containing an array of unshifted ingredient
s. 我期待console.log(dish)
记录的dish
与对象ingredients
含有的未移位的一个数组属性ingredient
秒。
When I log dish.ingredients
, it logs the ingredients. 当我记录dish.ingredients
成分时,它记录成分。
When I log dish
, it logs the dish
objects without the ingredients. 当我记录dish
,它记录dish
没有成分的东西。
Why is this? 为什么是这样?
for (let dish of dishArray) {
dish['ingredients'] = []
for (let ingredient of ingredientsArray) {
if (dish._id.equals(ingredient._dishID)) {
dish['ingredients'].unshift(ingredient)
}
}
console.log(dish['ingredients']) <-------------
console.log(dish) <-------------
}
dishArray
is an array of dish
objects returned from a mongoose query. dishArray
是从猫鼬查询返回的dish
对象数组。
Without further knowledge of your code, plain javascript ==
will do the job 无需进一步了解您的代码,普通的javascript ==
完成工作
var dishArray = [{ _id: '0' }, { _id: '1' }]; var ingredientsArray = [{ _id: '0', _dishID: '0' }, { _id: '1', _dishID: '1' }]; for (let dish of dishArray) { dish['ingredients'] = []; for (let ingredient of ingredientsArray) { if (dish._id == ingredient._dishID) { dish['ingredients'].unshift(ingredient); } } console.log(dish['ingredients']); console.log(dish); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.