Home > Web Front-end > JS Tutorial > How Can I Access JavaScript Object Properties Dynamically Using Their Names as Strings?

How Can I Access JavaScript Object Properties Dynamically Using Their Names as Strings?

Barbara Streisand
Release: 2024-12-23 10:21:10
Original
615 people have browsed it

How Can I Access JavaScript Object Properties Dynamically Using Their Names as Strings?

Accessing JavaScript Object Properties by Name as a String

When working with JavaScript objects, it is often necessary to access properties dynamically based on their names stored in a variable or returned from a function. Here's how to achieve this:

Using Bracket Notation

The preferred method for accessing properties using a variable is to use bracket notation:

function read_prop(obj, prop) {
    return obj[prop];
}
Copy after login

For example, to access the 'right' property of the given object:

var side = read_prop(columns, 'right');
Copy after login

This is equivalent to the dot notation:

var side = columns.right;
Copy after login

Nested Object Properties

To access properties of nested objects, use multiple brackets:

var cx = foo['c']['x'];
Copy after login

Undefined Properties

Accessing an undefined property will return 'undefined':

foo['c']['q'] === undefined; // true
Copy after login

Conclusion

Using bracket notation provides a flexible way to access JavaScript object properties by name as a string, whether it's a simple or nested property. It allows for more dynamic property access, especially when working with dynamic data or unknown property names.

The above is the detailed content of How Can I Access JavaScript Object Properties Dynamically Using Their Names as Strings?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template