reactjs - 在数组中添加属性。添加所有数组中的最后一个值
问题描述
“我在 forEach 循环中在数组上添加一个属性。但是当我执行 console.log() 时,每个数组上的附加值始终是 foreach 循环的最后一个值。”
交货数据有位置,我想将位置传递给pickupDetails。
deliveries: [{ //data of deliveries that I want to pass in pickupDetails
0: {Location: Korea},
1: {Location: Japan}
}]
let pickupDetails = this.state.pickupDetails;
//pickupDetails is only one object then It will become two since the deliveries has 2 objects
pickupDetails = {
name: "June"
}
this.state.deliveries.forEach((delivery, index) => {
pickupDetails.location = delivery.location;
console.log(pickupDetails)
})
the result of the console:
pickupDetails = {
name: "June"
location: "Japan" //this should be Korea since the first loop data is korea
}
pickupDetails = {
name: "June"
index: "Japan"
}
解决方案
我认为该代码中缺少某些内容可能是因为它的虚拟数据。好吧,从我的角度来看,您对 javascript 参考感到困惑。
deliveries: [{ //data of deliveries that I want to pass in pickupDetails
0: {Location: Korea},
1: {Location: Japan}
}]
let pickupDetails = this.state.pickupDetails;
this.state.deliveries.forEach((delivery, index) => {
let newPickupDetails = JSON.parse(JSON.stringify(pickupDetails));
newPickupDetails.location = delivery.location;
console.log(newPickupDetails);
})
the result of the console:
pickupDetails = {
name: "Juan"
location: "Japan" //this should be Korea since the first loop data is korea
}
pickupDetails = {
name: "June"
index: "Japan"
}
JSON.parse 和 JSON.stringify 我们用于创建新对象而不是使用引用。控制台日志受到影响,因为它通过引用链接,所以如果你将它设为新对象,它就会这样做。
检查变量 newPickupDetails
推荐阅读
- python - 将(在 Pandas 中)应用于多列
- python - 缩短异常的堆栈跟踪?
- python - 我的 for 循环和 while 循环在特定数字处停止
- javascript - 通过 Meteor 返回 blob 总是导致空对象
- wordpress - 帖子标题高度根据文本长度而变化
- ansible - Ansbile 从任务输出中获取子字符串
- django-queryset - 联合查询集未给出预期结果,是 Django ORM 错误吗?
- javascript - 鼠标悬停时垂直滚动 div
- python - 使用 Python 2020 请求登录 Facebook
- javascript - 如何将按钮列添加到 Ag Grid Javascript 网格