Q:

How to Dynamically Access Object Property Using Variable in JavaScript

0

How to Dynamically Access Object Property Using Variable in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the Square Bracket ([]) Notation

There are two ways to access or get the value of a property from an object — the dot (.) notation, like obj.foo, and the square bracket ([]) notation, like obj[foo].

Where the dot notation is easier to read and write, the square bracket notation offers much more flexibility since the value between the brackets can be any variable or expression.

Therefore, if you've an object's property name stored in a JavaScript variable, you can get its value using the square bracket notation, as shown in the following example:

<script>
// Sample JS object
var obj = {
    name: "Peter Parker",
    age: 16,
    country: "United States"
}
    
// Property name stored in JS variable
var prop = 'name';
    
// Accessing property value
alert(obj[prop]); // Outputs: Peter Parker
</script>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Append Values to an Array in JavaScript... >>
<< How to Split a String into an Array of Characters ...