How to Dynamically Access Object Property Using Variable in JavaScript
source link: https://www.laravelcode.com/post/how-to-dynamically-access-object-property-using-variable-in-javascript
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to Dynamically Access Object Property Using Variable in JavaScript
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>
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Recommend
-
5
AbstractWe have developed and implemented techniques that double the performance of dynamically-typed object-oriented languages. Our SELF implementation runs twice as fast as the fastest Smalltalk implementation,...
-
11
Using Python to Get an Object's Methods / Attributes Dynamically Oct 24, 2019 I'm a Ruby guy who is learning python...
-
8
Introduction Hi! Fellow developers, once again, another article (from your very own Mr. Jin Vincent Necesario). I often hang out at C# Corner to contribute and read articles. While b...
-
2
2 Ways to Remove a Property from an Object in JavaScriptA JavaScript object is a collection of properties, where each property has a name and a value. const employee = { name: 'John Smith', position: 'Sales Ma...
-
13
How to Check If an Object Property is Undefined in JavaScript 972 views 1 year ago Javascript
-
8
Introduction Hi! Fellow developers, once again, another article (from your very own Mr. Jin Vincent Necesario). I often hang out at C# Corner to contribute and read articles. While b...
-
6
-
7
-
12
How to access laravel pagination protected object property? 17452 views 2 years ago Laravel Hello, everyone in this...
-
1
TypeOfNaNHow to access an object property with a dynamically-computed name in JavaScriptNick ScialliMarch 18, 2023Using a dynamic objec...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK