This actually might be a JavaScript question, but it is happening when I am using AngularJs.
Say I have an array like this:
var players = [
{
id: 1,
name: 'Player 1'
},
{
id: 2,
name: 'Player 2'
}
];
and then I have another array like this:
var teams = [
{
id: 1,
name: 'Team 1',
members: players
},
{
id: 2,
name: 'Team 2',
members: players
}
];
If I decide to add a new property called position to one of the teams:
teams[0].members[0].position = 1;
I don't want it to then update the second team members position. I hope that makes sense.
Here is a codepen to illustrate my issue:
Array in java-script are mutable so you need to make copy of player and assign it to teams member property.
Just change your code to :
var teams = [
{
id: 1,
name: 'Team 1',
members: angular.copy(players)
},
{
id: 2,
name: 'Team 2',
members: angular.copy(players)
}
];
for more information see : https://docs.angularjs.org/api/ng/function/angular.copy
The only way (if both teams have the same players) is to use a copy of the array for the second team. Now it's logical the second team gets updated, because both teams point to the same reference of players
.
You can use angular.copy for that.
var copyofplayers = [];
angular.copy(players, copyofplayers);
also can use jQuery.extend() like
var teams = [
{
id: 1,
name: 'Team 1',
members: jQuery.extend({}, players)
},
{
id: 2,
name: 'Team 2',
members: jQuery.extend({}, players)
}
];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.