Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a copy of object in javascript/vuejs [duplicate]

I'm working with js object, lets say:

items: [{text: 'text1', active: true},
{text: 'text1', active: true},
{text: 'text1', active: true}]

I want to make the copy of the object and make some changes with them in computed property like this way:

computed: {
   copyAndChange() {
      var itemsCopy = []
      itemsCopy = this.items
      for (var i=0; i<itemsCopy.length; i++) {
         itemsCopy[i].text = "something"
         console.log('text from items: ' + this.item[i])
         console.log('text from itemsCopy: ' + itemsCopy[i])
      }
      return itemsCopy
   }
}

This code gives me in console:

text from items: something
text from itemsCopy: something
text from items: something
text from itemsCopy: something
text from items: something
text from itemsCopy: something

(?) why? I expected:

This code gives me in console:
text from items: text1
text from itemsCopy: something
text from items: text1
text from itemsCopy: something
text from items: text1
text from itemsCopy: something

what is wrong here?

like image 505
gileneusz Avatar asked Feb 28 '18 11:02

gileneusz


Video Answer


1 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();
like image 150
Chris Avatar answered Sep 28 '22 08:09

Chris