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

1

I have an angular problem

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, how can I execute it?

I've tried it like this and nothing is right

user.attr;
user.{attr};
user.(attr);
    
asked by anonymous 26.10.2017 / 22:21

3 answers

3

If I understand you 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 .

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

for (var x in usuario) {
   console.log(usuario[x]);
}
    
26.10.2017 / 22:27
0
 user = {name: 'Alexandre', email: '[email protected]'}

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

 console.log(attr , attr2) retorna => "Alexandre" "[email protected]"
    
26.10.2017 / 22:31