【发布时间】:2021-11-12 10:55:14
【问题描述】:
我想为每个employeeID 更新对象中的数组。 我的“选定”数组有要添加的员工 ID。 该函数为所有员工添加相同的时间和工作,但在每次迭代之后,所有 emplyeeID 都是最后推送的emplyeeID。
selected = [ "01PILGAR", "01DERREX", "01SANJAC" ]
updatePersonnelTime() {
console.log("updatePersonnelTime", this.time);
var newtime = this.time;
newtime.controlDateTime = new Date();
if(!this.currentJob.time){
this.currentJob.time = [];
}
for (let i=0; i < this.selected.length; i++){
newtime.employeeID = this.selected[i];
console.log('this.selected[i]: ', this.selected[i]);
this.currentJob.time.push(newtime);
console.log('this.time: ', this.currentJob);
}
this.updateJob();
this.timeRows = this.currentJob.time
},
这将向数组中添加三个时间信息,所有的员工ID 都为“01SANJAC” 当我查看每次推送时,employeeID 会显示正在推送的数组中的每个项目。
为什么最终数组中的所有项目都具有最后一个employeeID 值?
最终数组 =
[
{ "task": "1000", "inout": { "label": "In", "value": 1 }, "time": "08:00", "detailNotes": "time", "officeNotes": "office time", "controlDateTime": "2021-09-17T14:54:13.371Z", "employeeID": "01SANJAC" },
{ "task": "1000", "inout": { "label": "In", "value": 1 }, "time": "08:00", "detailNotes": "time", "officeNotes": "office time", "controlDateTime": "2021-09-17T14:54:13.371Z", "employeeID": "01SANJAC" },
{ "task": "1000", "inout": { "label": "In", "value": 1 }, "time": "08:00", "detailNotes": "time", "officeNotes": "office time", "controlDateTime": "2021-09-17T14:54:13.371Z", "employeeID": "01SANJAC" }
]
这就是为我解决的问题:
updatePersonnelTime() {
console.log("updatePersonnelTime", this.time);
var newtime = this.time;
newtime.controlDateTime = new Date();
if(!this.currentJob.time){
this.currentJob.time = [];
}
for (let i=0; i < this.selected.length; i++){
newtime.employeeID = this.selected[i];
console.log('this.selected[i]: ', this.selected[i]);
// added 'Object.assign in the push
this.currentJob.time.push(Object.assign({}, newtime));
console.log('this.time: ', this.currentJob);
}
this.updateJob();
this.timeRows = this.currentJob.time
},
【问题讨论】:
-
你一遍又一遍地推动同一个对象。对
.push()的调用不会复制。 -
是的,同一对象更改了employeeID。我如何正确推动这个?
-
您需要在某个时候制作对象的副本。
-
我看到复制对象的帖子,但仍然不确定如何用于保存我的数组??
-
复制原始对象,设置员工id,推送。
标签: javascript arrays vue.js for-loop