[Solved] How to access property of JavaScript object, given string with property’s name


Let’s look at the code you’re trying to use:

$http.get( 
'url' 
) 
.success(function(data) {
    var response = angular.fromJson(data); 
    var mobilereceiver="0147852369"; 
    var messageId = response.ok.mobilereciever; 
});

You’re very close, in that you recognize that your string mobilereceiver holds the value that needs to be provided as the name of the final property. However, on your last line, when you try to access response.ok.mobilereceiver, that isn’t actually referring to the variable mobilereceiver. Instead, it’s just looking for a property inside ok that’s actually called mobilereceiver. Instead of trying to use the dot notation for accessing properties, what you need to do is use the associative array style accessor:

var messageId = response.ok[mobilereceiver];

This will allow the actual value of mobilereceiver to be passed in as a string, which will be used as the key to look up the value you’re trying to access.

0

solved How to access property of JavaScript object, given string with property’s name