How to concatenate an object with a variable to be dynamic?

Asked

Viewed 801 times

1

Guys I have trouble in angular

I have my object

user = {name: 'Alexandre', email: '[email protected]'}

I need a way to show on the console

    var attr  = 'name';
    var attr2 = 'email';
    insira o código aqui
    console.log(user.attr) e me retorne Alexandre;
    console.log(user.attr2) e me retorne '[email protected];

The second parameter of the object would be dynamically variable, as I can execute?

I’ve tried it like this and nothing right

user.attr;
user.{attr};
user.(attr);

3 answers

3


If I understand correctly, you can access the properties of the object using the following notation:

var attr  = 'name';
var attr2 = 'email';

console.log(user[attr]) // mesmo que "user.name"
// => 'Alexandre'

console.log(user[attr2]) // mesmo que "user.email"
// => '[email protected]'

More information here.

  • Thank you I didn’t know you could access as an array type

1

var user = '{"name": "Alexandre", "email": "[email protected]"}';
var usuario = JSON.parse(user);

for (var x in usuario) {
   console.log(usuario[x]);
}
  • problem nor is this, problem and show with variable.

  • I don’t think I understand it very well. It may be clearer?

  • i have a user object in it contain name,email I will receive these 2 parameters dynamically or be will become user. $variable and user. $variable2

  • Now I think I understand.Look at my edited answer.

  • So what? It worked?

0

Browser other questions tagged

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