I have 2 objects: one of them contains the player list and the other one contains players in loading screen.
When i remove a player from playersNotReady object, it also removes the player from the player list and i don't want that.
var players = {
1: "Player1",
2: "Player2"
};
var playersNotReady = players;
delete playersNotReady[1];
console.log(players); // {2: "Player2"}
console.log(playersNotReady); // {2: "Player2"}
Why is this happening and how can i remove player from playersNotReady object without removing them from the actual player list?
You are not creating a new variable. You are just pointing by reference. You can use Object.assign
to clone/create new object.
var players = {
1: "Player1",
2: "Player2"
};
var playersNotReady = Object.assign({}, players);
delete playersNotReady[1];
console.log(players);
console.log(playersNotReady);
Doc: Object.assign
One option also, is to use Destructuring Assignment
, Like:
var players = {
1: "Player1",
2: "Player2"
};
var {1: p1,...playersNotReady} = players; //This will create a new object and remove the 1
console.log(players);
console.log(playersNotReady);
Doc: Spread
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments