我正在尝试将数组元素的值分配给对象。在第一次尝试之后,例如 bar = foo[0];
我发现对 bar
的任何更改也会更改 foo[0]
, 由于具有相同的引用。
太棒了,没有人想到,在阅读了不变性和 ES6 Object.assign() 方法和spread 属性后,我认为它会解决这个问题。但是,在这种情况下它不会。我错过了什么?
编辑:对于 accountTypes 的混淆,我深表歉意,我修复了示例。
另外,我想保留 Settings 的类结构,所以 let copy = JSON.parse(JSON.stringify(original));
并不是我真正想要的在这种情况下之后。
//this object will change according to a selection
currentPreset;
//this should remain unchanged
presets: {name: string, settings: Settings}[] = [];
ngOnInit()
{
this.currentPreset = {
name: '',
settings: new Settings()
}
this.presets.push({name: 'Preset1', settings: new Settings({
settingOne: 'foo',
settingTwo: false,
settingThree: 14
})
});
}
/**
* Select an item from the `presets` array and assign it,
* by value(not reference), to `currentPreset`.
*
* @Usage In an HTML form, a <select> element's `change` event calls
* this method to fill the form's controls with the values of a
* selected item from the `presets` array. Subsequent calls to this
* method should not affect the value of the `presets` array.
*
* @param value - Expects a numerical index or the string 'new'
*/
setPreset(value)
{
if(value == 'new')
{
this.currentPreset.name = '';
this.currentPreset.settings.reset();
}
else
{
this.currentPreset = {...this.presets[value]};
//same as above
//this.currentPreset = Object.assign({}, this.presets[value]);
}
}
最佳答案
试试这个:let copy = original.map(item => Object.assign({}, ...item));
这将创建一个新对象,而不引用旧对象 original
如果您想对数组执行此操作,请尝试使用 []
let copy = original.map(item => Object.assign([], ...item));
关于javascript - Object.assign() 和 Spread 属性仍在改变原始属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50010725/