8

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?

0

1 Answer 1

16

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

Sign up to request clarification or add additional context in comments.

10 Comments

oh I see... but using this.items.slice(); gives me the same result...
@gileneusz, sorry. Forgot that your array had objects. See my update above.
I'm checking...
are you sure you didn't forget anything? Did you do both the slice() and the Object.assign()?
oh, I miss slice(), now it works. The only difference is that in vue I've changed itemsCopy = items.slice(); into 'this.items.slice();'. Thank you for help!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.