Converting data into Javascript

Asked

Viewed 45 times

0

I wonder if I can do what is explained in the code below.. :

isString = 'nomeUsuario=Bruno'; // String 
toArray = isString.split('='); // Retira o = da String e converte toArray para Array ["nomeUsuario", "Bruno"]
console.log(toArray); // Exibe Array ["nomeUsuario", "Bruno"]
console.log(toArray[0]); // Exibe o nomeUsuario
console.log(toArray[1]); // Exibe o Bruno
/** 
  * Queria saber se posso usar o nomeUsuraio (toArray[0]) 
  * para receber o valor de Bruno (toArray[1]) como o JavaScript
  * faz com uma variável --- exemplo: var nomeUsuario = 'Bruno', ...
  * console.log(nomeUsuario); // imprime Bruno ..
 **/

  • I believe you are working with a url, no?

  • no, just wondering if I can do something as explained above...

  • 2

    Well, in that case you can use window[toArray[0]] = toArray[1]; console.log(nomeUsuario);

  • That is, you want to implement reflection in JS?

  • helped, I’m still knowing the javascript.

  • Detail to use window not always a good choice if you are working with multiple scopes for example. Using window you create a variable in the global scope, which can influence other js codes in your system

  • Is there another way to display this result?

  • Create an empty variable and assign it to it, would it work? The same way you would be doing with the window, variavelQualquer[toArray[0]]

  • It would be easier to show how you want to use this result, or what you will do with it, because you will certainly have other better ways of doing what you want. In the case cited console.log(toArray[0]); gives the result you want, because you need to define the variable nomeUsuario ?

  • this depends on where I removed the string, there are certainly other possibilities to define a value for your nameUsuario, but this is not the case..

Show 5 more comments

1 answer

0

I believe that what you want would not be with an array itself, but with an object... for example you could do.:

var objeto = { nomeUsuario: 'Bruno'} //Atribui Bruno para a a propriedade nomeUsuario 
console.log(objeto.nomeUsuario); //Imprimirá Bruno
  • not that - already solved, if you analyze the code you see what I wanted to do, the solution is in the comments of the question. thanks!

  • ah pasta... vlw !!

Browser other questions tagged

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