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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With