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

Asked

Viewed 66 times

0

I am Creating a card game that runs in the browser and I need that in some situations, there may be the same cards in different hands ("Computer" or Player). However, I don’t want to have to create another object to represent the enemy cards. This one below for example, is an object that represents a card.

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 this in the enemy’s hand 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 changed the id of Bherk_tropa_enemy the id of Bherk_tropa was also changed. I hope to get enlightenment through some good soul. I thank you give of now. XD

2 answers

2


Try with the Spread Operator. It will actually perform a copy of the object, and not point to the same reference:

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

Another way to do:

Object.assign({}, Bherk_tropa);

The operation will be the same.

  • It worked!! Thank you very much friend. But what this 'Let' does?

  • It initializes the variable, in case a Bherk_tropa_Inimigo, the same as var however has a smaller scope. If you use the code please accept as the correct answer. Thank you.

  • 1

    Vlw, thank you very much

0

If it’s not an inconvenience, the spread operator is not supported by Microsoft browsers.

You can use a for...in to insert the 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

  • 1

    thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.