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











up vote
1
down vote

favorite












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.










share|improve this question






















  • Try using item.slice(0). davidwalsh.name/javascript-clone-array
    – Yaakov Ainspan
    Nov 7 at 21:40










  • item is an object, just one of its properties is an array
    – omega
    Nov 7 at 21:41










  • @YaakovAinspan: that won't deep clone the array, i.e., you will get a new array but it will still refer to the same objects as the original array. A deep clone of the array might look like: var newArray = item.theArray.map(a => Object.assign({}, a));. This basically does what OP is doing for the main object but applying it to the array as well. The problem is that I don't know of a one-liner, you might have to write a helper method.
    – Cᴏʀʏ
    Nov 7 at 21:41












  • also, the item is arbitrary so I can't hardcode its properties name.
    – omega
    Nov 7 at 21:42










  • is stringify, and parse the best option?
    – omega
    Nov 7 at 21:43















up vote
1
down vote

favorite












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.










share|improve this question






















  • Try using item.slice(0). davidwalsh.name/javascript-clone-array
    – Yaakov Ainspan
    Nov 7 at 21:40










  • item is an object, just one of its properties is an array
    – omega
    Nov 7 at 21:41










  • @YaakovAinspan: that won't deep clone the array, i.e., you will get a new array but it will still refer to the same objects as the original array. A deep clone of the array might look like: var newArray = item.theArray.map(a => Object.assign({}, a));. This basically does what OP is doing for the main object but applying it to the array as well. The problem is that I don't know of a one-liner, you might have to write a helper method.
    – Cᴏʀʏ
    Nov 7 at 21:41












  • also, the item is arbitrary so I can't hardcode its properties name.
    – omega
    Nov 7 at 21:42










  • is stringify, and parse the best option?
    – omega
    Nov 7 at 21:43













up vote
1
down vote

favorite









up vote
1
down vote

favorite











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.










share|improve this question













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.







javascript






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 7 at 21:36









omega

9,45844128256




9,45844128256












  • Try using item.slice(0). davidwalsh.name/javascript-clone-array
    – Yaakov Ainspan
    Nov 7 at 21:40










  • item is an object, just one of its properties is an array
    – omega
    Nov 7 at 21:41










  • @YaakovAinspan: that won't deep clone the array, i.e., you will get a new array but it will still refer to the same objects as the original array. A deep clone of the array might look like: var newArray = item.theArray.map(a => Object.assign({}, a));. This basically does what OP is doing for the main object but applying it to the array as well. The problem is that I don't know of a one-liner, you might have to write a helper method.
    – Cᴏʀʏ
    Nov 7 at 21:41












  • also, the item is arbitrary so I can't hardcode its properties name.
    – omega
    Nov 7 at 21:42










  • is stringify, and parse the best option?
    – omega
    Nov 7 at 21:43


















  • Try using item.slice(0). davidwalsh.name/javascript-clone-array
    – Yaakov Ainspan
    Nov 7 at 21:40










  • item is an object, just one of its properties is an array
    – omega
    Nov 7 at 21:41










  • @YaakovAinspan: that won't deep clone the array, i.e., you will get a new array but it will still refer to the same objects as the original array. A deep clone of the array might look like: var newArray = item.theArray.map(a => Object.assign({}, a));. This basically does what OP is doing for the main object but applying it to the array as well. The problem is that I don't know of a one-liner, you might have to write a helper method.
    – Cᴏʀʏ
    Nov 7 at 21:41












  • also, the item is arbitrary so I can't hardcode its properties name.
    – omega
    Nov 7 at 21:42










  • is stringify, and parse the best option?
    – omega
    Nov 7 at 21:43
















Try using item.slice(0). davidwalsh.name/javascript-clone-array
– Yaakov Ainspan
Nov 7 at 21:40




Try using item.slice(0). davidwalsh.name/javascript-clone-array
– Yaakov Ainspan
Nov 7 at 21:40












item is an object, just one of its properties is an array
– omega
Nov 7 at 21:41




item is an object, just one of its properties is an array
– omega
Nov 7 at 21:41












@YaakovAinspan: that won't deep clone the array, i.e., you will get a new array but it will still refer to the same objects as the original array. A deep clone of the array might look like: var newArray = item.theArray.map(a => Object.assign({}, a));. This basically does what OP is doing for the main object but applying it to the array as well. The problem is that I don't know of a one-liner, you might have to write a helper method.
– Cᴏʀʏ
Nov 7 at 21:41






@YaakovAinspan: that won't deep clone the array, i.e., you will get a new array but it will still refer to the same objects as the original array. A deep clone of the array might look like: var newArray = item.theArray.map(a => Object.assign({}, a));. This basically does what OP is doing for the main object but applying it to the array as well. The problem is that I don't know of a one-liner, you might have to write a helper method.
– Cᴏʀʏ
Nov 7 at 21:41














also, the item is arbitrary so I can't hardcode its properties name.
– omega
Nov 7 at 21:42




also, the item is arbitrary so I can't hardcode its properties name.
– omega
Nov 7 at 21:42












is stringify, and parse the best option?
– omega
Nov 7 at 21:43




is stringify, and parse the best option?
– omega
Nov 7 at 21:43












2 Answers
2






active

oldest

votes

















up vote
0
down vote













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.






share|improve this answer




























    up vote
    0
    down vote













    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.







    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














       

      draft saved


      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53198197%2fhow-to-do-object-assign-but-create-new-copies-of-arrays-in-javascript%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      0
      down vote













      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.






      share|improve this answer

























        up vote
        0
        down vote













        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.






        share|improve this answer























          up vote
          0
          down vote










          up vote
          0
          down vote









          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.






          share|improve this answer












          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.






          //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);





          //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);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 7 at 21:45









          zfrisch

          4,19111024




          4,19111024
























              up vote
              0
              down vote













              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.







              share|improve this answer

























                up vote
                0
                down vote













                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.







                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  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.







                  share|improve this answer












                  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.








                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 7 at 21:47









                  Sergii Korh

                  565




                  565






























                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53198197%2fhow-to-do-object-assign-but-create-new-copies-of-arrays-in-javascript%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      這個網誌中的熱門文章

                      Xamarin.form Move up view when keyboard appear

                      Post-Redirect-Get with Spring WebFlux and Thymeleaf

                      Anylogic : not able to use stopDelay()