Angular 4个拼接复制数组对象
Angular 4 splice duplicating array objects
我针对这个问题简化了一些代码。
this.getDataRuleList.splice(this.count, 1, dataRuleData);
console.log(this.getDataRuleList);
this.count += 1;
getDataRuleList 正在从服务返回一组对象。它还可以毫无问题地绑定到 PrimeNg TurboTable。
// get method to get service collection
get getDataRuleList(): IDataRule[] {
return this._dataRuleListService.dataRuleList;
}
当我编辑一行时,我试图通过用新对象替换整个对象来更新绑定数组 (getDataRuleList) 中的对象。我正在为此使用拼接方法。问题是,我替换的每个对象都变得相同(为了更好地理解,请参见图片)。我粘贴在拼接值位置的值每次都不同(dataRuleData),但我所有的数组元素都变成了这个值。我假设它与引用有关,但我怎样才能避免这种情况发生?
image of issue
const cloneData = Object.assign({},dataRuleData);
this.getDataRuleList.splice(this.count, 1,cloneData);
如果你需要使用深度克隆你可以检查this example
const deepCloneData = JSON.parse(JSON.stringify(obj1));
你可以为克隆体使用 es6 拼接运算符
例子
const cloneData = {...dataRuleData};
我针对这个问题简化了一些代码。
this.getDataRuleList.splice(this.count, 1, dataRuleData);
console.log(this.getDataRuleList);
this.count += 1;
getDataRuleList 正在从服务返回一组对象。它还可以毫无问题地绑定到 PrimeNg TurboTable。
// get method to get service collection
get getDataRuleList(): IDataRule[] {
return this._dataRuleListService.dataRuleList;
}
当我编辑一行时,我试图通过用新对象替换整个对象来更新绑定数组 (getDataRuleList) 中的对象。我正在为此使用拼接方法。问题是,我替换的每个对象都变得相同(为了更好地理解,请参见图片)。我粘贴在拼接值位置的值每次都不同(dataRuleData),但我所有的数组元素都变成了这个值。我假设它与引用有关,但我怎样才能避免这种情况发生?
image of issue
const cloneData = Object.assign({},dataRuleData);
this.getDataRuleList.splice(this.count, 1,cloneData);
如果你需要使用深度克隆你可以检查this example
const deepCloneData = JSON.parse(JSON.stringify(obj1));
你可以为克隆体使用 es6 拼接运算符
例子
const cloneData = {...dataRuleData};