Reputation: 181
I have made a js file in which data is being fetched from js file and the values are stored in a request object. Example of JSON file
{
"name": "ABC",
"age": 20
}
I want to display the value of name using variable name. I want something like this.
var x = "name";
var req = JSON.parse(request.responseText);
console.log(req.x);
But the above statement displays undefined. Any solutions?
Upvotes: 1
Views: 70
Reputation: 10396
Use brackets instead of dot:
var x = "name";
var req = {
"name": "ABC",
"age": 20
};
console.log(req[x]);
You need to use brackets here because the name of the property is dynamic, with the value coming from a variable (dot should be used only when the name of the property is static)
Upvotes: 4