[英]How to do object assign but create new copies of arrays in javascript?
我有這個代碼
this.data_table.editedIndex = this.data_table.items.indexOf(item);
this.data_table.editedItem = Object.assign({}, item);
this.data_table.edit.tabs.currentTab = 0;
this.data_table.dialog = true;
但我注意到一個問題,當item
具有數組時,我認為同一數組會放入新對象中。 我如何更改它以使其成為陣列的新副本? 最好是陣列的深層副本。
無需使用Object.assign
創建一個遍歷對象的幫助器方法,而是確定一個值是否為數組,並使用一個spread operator ( ... )
顯式復制它spread operator ( ... )
let copyObj = o => {
let new_o = {};
for (let k of Object.keys(o)) {
(Array.isArray(o[k])) ? new_o[k] = [...o[k]]: new_o[k] = o[k];
}
return new_o;
}
//create copy function let copyObj = o => { let new_o = {}; for (let k of Object.keys(o)) { (Array.isArray(o[k])) ? new_o[k] = [...o[k]]: new_o[k] = o[k]; } return new_o; }, //our object obj = { aString: "hola!", anArray: [1, 2, 3, 4, 5, 6] }, //our new object nObj = copyObj(obj); //change the old object obj.anArray[3] = 555555; //the old object array is changed, but the new one isn't. console.log("new object: ", nObj, "old object: ", obj);
請注意,要深度克隆Array並從Array的第一級或更深的級別返回全新的Objects和Array,您將在更多條件下實現相同的技術,然后遞歸調用該函數。
Lodash會成功的。 嘗試方法_.merge(obj1, obj2)
https://lodash.com/docs/4.17.11#merge
數組和普通對象屬性以遞歸方式合並。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.