简体   繁体   中英

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. 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 ( ... )

   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.

Lodash will do the trick. Try method _.merge(obj1, obj2) https://lodash.com/docs/4.17.11#merge

Array and plain object properties are merged recursively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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