如何动态传递Object.assign?
假设这是我的对象:
this.driverForm.value.drivers
0:{last_name: "Are", first_name: "", gender: "", dob: "", address: "", …}
现在我可以轻松地分配这样的对象:
const submittedForm = Object.assign(
{}, this.driverForm.value.drivers[0],
);
但是如果我的值改变如下,我将如何分配对象:
0:{last_name: "Are", first_name: "", gender: "", dob: "", address: "", …}
1:{last_name: "Wert", first_name: "", gender: "", dob: "", address: "", …}
这是完整的代码
saveNewDriver() {
console.log(this.driverForm.value.drivers,'driver save');
const submittedForm = Object.assign(
{}, this.driverForm.value.drivers[0], {enable: true},
{checked: false},
);
this.store.select('drivers').dispatch(new createDriver(submittedForm));
}
答案 0 :(得分:1)
我不知道我是否做了正确的事,但我让它发挥作用
saveNewDriver() {
const myarray = this.driverForm.value.drivers;
const submittedForm = myarray.map(a => ({...a, enable: true, checked: false}));
submittedForm.forEach(driver => {
this.store.select('drivers').dispatch(new createDriver(driver));
});
}
请让我知道更优雅的解决方案
答案 1 :(得分:0)
由于您应该避免混合基于数字的属性(如数组中的'0'
)和命名属性(如'enable'
),我强烈建议您根据每个驱动程序对象创建一个数组: / p>
saveNewDriver() {
console.log(this.driverForm.value.drivers,'driver save');
const submittedForms = this.driverForm.value.drivers.map(driver =>
Object.assign({},
driver,
{enable: true},
{checked: false}
);
);
submittedForms.forEach(form => {
this.store.select('drivers').dispatch(new createDriver(form));
});
}
答案 2 :(得分:0)
我假设您不想改变this.driverForm并向this.driverForm.value.drivers添加新项目
this.driverForm = Object.assign(
{},
this.driverForm,
{value:Object.assign(
{},
this.driverForm.value,
{drivers:this.driverForm.value.drivers.concat(newDriver)}
)}
)
使用spread运算符,它看起来像这样:
this.driverForm = {
...this.driverForm,
value:{
...this.driverForm.value,
drivers:this.driverForm.value.driverForm.concat(newDriver)
}
}