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
Barbara StreisandOriginal
2024-12-23 10:21:10610browse

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];
}

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

var side = read_prop(columns, 'right');

This is equivalent to the dot notation:

var side = columns.right;

Nested Object Properties

To access properties of nested objects, use multiple brackets:

var cx = foo['c']['x'];

Undefined Properties

Accessing an undefined property will return 'undefined':

foo['c']['q'] === undefined; // true

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!

Statement:
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