Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  47] [ 6]  / answers: 1 / hits: 27524  / 6 Years ago, wed, february 28, 2018, 12:00:00

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?


More From » vue.js

 Answers
5

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




[#55047] Saturday, February 24, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tinakimv

Total Points: 126
Total Questions: 90
Total Answers: 104

Location: Netherlands
Member since Mon, Jun 7, 2021
3 Years ago
;