How to assign all the characteristics of one object to another, least one in particular?

0

I'm creating a card game that runs in the browser and I need in some situations, there may be the same cards in different hands ("Computer" or "Player"). However, I do not want to have to create another object to represent the enemy cards. This is just below for example, and an object that represents a letter.

Bherk_tropa = {
  nome: 'Bherk',
  raca: 'Anão',
  classe: 'Clerigo',
  id: 'Bherk',

  corpo_a_corpo: true,
  pesadas: true,
  longo_alcance: true,
  armadadura: true,

  pvInical: 150,
  pontos_de_vida: 150,
  ataque: 70,
  defesa: 80,
  agilidade: 06,
  brutalidade: 13,
  Efeito: function(){

  }
}

To create another card similar to that in the enemy's hand by changing only the attribute and id for example, I tried the following line of code:

Bherk_tropa_Inimigo = Bherk_tropa;
Bherk_tropa_Inimigo.id = "BherInimigo";

But the result was that when you changed the id of Bherk_tropa_Inimigo the id of Bherk_tropa was also changed. I hope to gain enlightenment through some good soul. Thanks in advance. XD

    
asked by anonymous 23.05.2018 / 21:55

2 answers

2

Try using the Spread operator . It will actually hold a copy of the object, not point to the same reference:

let Bherk_tropa_Inimigo = {...Bherk_tropa};
Bherk_tropa_Inimigo.id = "BherInimigo";

Another way to do it:

Object.assign({}, Bherk_tropa);

The operation will be the same.

    
23.05.2018 / 22:26
0
  

If this is not an inconvenience, the spread operator is not supported by   browsers.

You can use for...in to insert keys and their values from one object to another:

var Bherk_tropa = {
  nome: 'Bherk',
  raca: 'Anão',
  classe: 'Clerigo',
  id: 'Bherk',

  corpo_a_corpo: true,
  pesadas: true,
  longo_alcance: true,
  armadadura: true,

  pvInical: 150,
  pontos_de_vida: 150,
  ataque: 70,
  defesa: 80,
  agilidade: 06,
  brutalidade: 13,
  Efeito: function(){
  }
}

var Bherk_tropa_Inimigo = {}; // cria o novo objeto

for(key in Bherk_tropa){
    Bherk_tropa_Inimigo[key] = Bherk_tropa[key]; // copia as chaves
}

Bherk_tropa_Inimigo.id = "BherInimigo"; // altera a chave "id"

console.log(Bherk_tropa.id); // mostra o valor de "id" no objeto original
console.log(Bherk_tropa_Inimigo.id); // mostra o novo valor de "id" no novo objeto
console.log(Bherk_tropa_Inimigo); // mostra o novo objeto completo
    
23.05.2018 / 22:28