0

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?

Satpal
  • 132,252
  • 13
  • 159
  • 168
party34
  • 99
  • 3
  • 14
  • 1
    You have to clone the object for playersNotReady because players and playersNotReady share the same object. – Powkachu Mar 28 '18 at 08:58
  • 1
    *"Why is this happening?"* -- the statement `var playersNotReady = players;` does not duplicate the value of `players`. It just adds a new reference to it. The object you create in the first lines of code can now be accessed through two variables: `players` and `playersNotReady`. – axiac Mar 28 '18 at 08:59

3 Answers3

1

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

Eddie
  • 26,593
  • 6
  • 36
  • 58
0

When you do var playersNotReady = players; you are not creating a new object, but simply a new reference to the players object, this is because objects are passed by reference in javascript.

To create a new object, you can use the ES6 spread operator: var playersNotReady = {...players};

bugs
  • 14,631
  • 5
  • 48
  • 52
0

while you assign var playersNotReady = players; it actually create a reference for players. not a new object. You can copy object by Object.assign.

var players = {
  1: "Player1",
  2: "Player2"
};
var playersNotReady = Object.assign({}, players);
delete playersNotReady[1];
console.log(players); // {2: "Player2"}
console.log(playersNotReady); // {2: "Player2"}
atiq1589
  • 2,227
  • 1
  • 16
  • 24