Set object key by a variable

Asked

Viewed 293 times

0

I have the following object

Perfil1 ["Souza", "4", "3"]
Perfil2 ["Pedro", "2", "1"]
Perfil3 ["Lucas", "5", "8"]

and a range from 1 to 10

how do i change the profile number of each key according to the for number

I tried to do so, but to no avail

//Number é o numero que o for gera
console.log(perfil.Perfil+Number);

Example:

var obj = [{  
   "Perfil1":[  
      "Pedro",
      "5",
      "1"
   ],
   "Perfil2":[  
      "Marcos",
      "2",
      "2"
   ],
   "Perfil3":[  
      "Joao",
      "2",
      "1"
   ]
}]

var numero = new Number();

var numero = 2;//Quero definir um numero aqui, por exemplo 2 para "Marcos"


console.log(obj[0].Perfil + numero);//Retorna NaN

console.log(obj[0].Perfil2);//Setando direto ele retorna o resultado

  • What would be "profile number"? It has how to make a [mcve]?

  • a moment I’ll make

  • This would no longer resolve the issue in Nan: console.log(obj[0]. Profile + '+ number) ?

  • It would be more semantic to use object array instead of array object array. You really need to follow this format?

2 answers

1


Objects in Javascript behave like value-key dictionaries, so you can access them by name.

console.log(obj[0]["Perfil" + numero]);

if the idea is to change the profile number, you can do it as follows.:

var obj = [{  
   "Perfil1":[ "Pedro", "5", "1" ],
   "Perfil2":[ "Marcos", "2", "2" ],
   "Perfil3":[ "Joao", "2", "1" ]
}]

var perfis = obj[0];
var trocarNumero = function (ori, dst) {
  if (perfis["Perfil" + ori] && !perfis["Perfil" + dst]) {
    var perfil = perfis["Perfil" + ori];
    perfis["Perfil" + dst] = perfil;
    delete perfis["Perfil" + ori];
  }
};

trocarNumero(1, 5);
console.log(perfis);

1

JSON forms a powerful data structure from which you can take better advantage. My suggestion is you change to a array of objects to represent the scenario.

Instead of:

[
   {
    A: [idx1, idx2],
    B: [idx1, idx2]
   }
]

Could be:

[{
    "nome": "A",
    "idade": "X",
    "numero": "Y"
}, {
    "nome": "B",
    "idade": "X",
    "numero": "Y"
}]

Example

var perfis = [{
    nome: "Pedro",
    idade: 20,
    numero: 10
  },
  {
    nome: "Marcos",
    idade: 30,
    numero: 20
  }
];
perfis[1].numero = 1; // altera o numero do perfil do Marcos
console.log(perfis[1]);

Browser other questions tagged

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