简体   繁体   English

如何在JavaScript中分配对象但创建数组的新副本?

[英]How to do object assign but create new copies of arrays in javascript?

I have this code 我有这个代码

        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;

but i'm noticing an issue where when the item has an array, i think the same array gets put in the new object. 但我注意到一个问题,当item具有数组时,我认为同一数组会放入新对象中。 How can I change it so that it makes a new copy of the array? 我如何更改它以使其成为阵列的新副本? Preferably a deep copy of the array. 最好是阵列的深层副本。

Instead of using Object.assign create a helper method to iterate through the object, determine if a value is an array and explicitly copy it using a spread operator ( ... ) 无需使用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); 

Note to deep clone the Array and return entirely new Objects and Arrays from within the first level of the Array or deeper, you would implement this same technique with further conditionals and recursively call the function. 请注意,要深度克隆Array并从Array的第一级或更深的级别返回全新的Objects和Array,您将在更多条件下实现相同的技术,然后递归调用该函数。

Lodash will do the trick. Lodash会成功的。 Try method _.merge(obj1, obj2) https://lodash.com/docs/4.17.11#merge 尝试方法_.merge(obj1, obj2) https://lodash.com/docs/4.17.11#merge

Array and plain object properties are merged recursively. 数组和普通对象属性以递归方式合并。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM