1

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?

4 Answers 4

4

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)

Sign up to request clarification or add additional context in comments.

Comments

1

It should be console.log(req[x]);

OR

console.log(req.name);

Comments

1

Use obj[key]

console.log(req[x]);

Comments

0

You can also use console.log(req.name)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.