Home >Web Front-end >JS Tutorial >How Can I Access JavaScript Object Properties Dynamically?

How Can I Access JavaScript Object Properties Dynamically?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 19:59:15595browse

How Can I Access JavaScript Object Properties Dynamically?

Accessing JavaScript Object Properties Dynamically by Name

Consider an object with boolean properties:

var columns = {
  left: true,
  center: false,
  right: false
};

To retrieve a property value dynamically based on a provided string variable, such as "right," you can use either bracket or dot notation.

Bracket Notation:

var side = columns['right'];

This method allows referencing property names stored in variables or obtained dynamically.

Dot Notation:

var side = columns.right;

Dot notation is ideal when the property name is a known string constant.

Function for Dynamic Property Access

If a function is preferred:

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

Nested Objects

Nested object properties can be accessed using multiple brackets or dot notation, e.g.:

var foo = { a: 1, b: 2, c: { x: 999, y: 998, z: 997 } };
var cx = foo['c']['x'];

Undefined Properties

If a property is undefined, referencing it will return undefined:

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

The above is the detailed content of How Can I Access JavaScript Object Properties Dynamically?. 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