how to make a copy of object in javascript/vuejs

This question already has an answer here:

  • How do I correctly clone a JavaScript object? 54 answers

  • You are not creating a copy. You are assigning the reference to this.items to your itemsCopy array. Thus, you are later mutating the same array.

    Create a copy with:

    itemsCopy = this.items.slice();
    

    The same issue applies with each object inside your array. In your loop, create a copy of the object:

    var obj = Object.assign({}, itemsCopy[i]);
    obj.text = "something";
    itemsCopy[i] = obj;  //replace the old obj with the new modified one.
    

    Demo:

    var items = [
      {text: 'text1', active: true},
      {text: 'text1', active: true},
      {text: 'text1', active: true}
    ];
    
    function copyAndChange() {
      var itemsCopy = []
      itemsCopy = items.slice();
      for (var i=0; i<itemsCopy.length; i++) {
        var obj = Object.assign({}, itemsCopy[i]);
        obj.text = "something";
        itemsCopy[i] = obj;  //replace the old obj with the new modified one.
        console.log('text from items: ' + items[i].text)
        console.log('text from itemsCopy: ' + itemsCopy[i].text)
      }
      return itemsCopy
    }
    
    copyAndChange();
    链接地址: http://www.djcxy.com/p/24780.html

    上一篇: 我怎样才能做一个深度嵌套状态的副本?

    下一篇: 如何在javascript / vuejs中创建对象的副本