Home > Web Front-end > JS Tutorial > How to Access JavaScript Object Properties Using a String for the Property Name?

How to Access JavaScript Object Properties Using a String for the Property Name?

Patricia Arquette
Release: 2024-12-18 08:38:13
Original
301 people have browsed it

How to Access JavaScript Object Properties Using a String for the Property Name?

Accessing JavaScript Object Property by Name as String

When working with JavaScript objects, it's often necessary to access properties by their names, which can be obtained dynamically or from user input. This question addresses how to write a function to retrieve a property value based on its name represented as a string.

Solution

The provided solution offers two approaches:

Bracket Notation:

This is the preferred method for accessing properties by name dynamically. It involves using brackets ([]), like:

var side = columns['right'];
Copy after login

Function (using bracket notation):

If you specifically require a function, you can use:

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

Nested Objects

If your object is nested, you can access property values using multiple brackets. For example, with the object:

var foo = { a: 1, b: 2, c: { x: 999, y: 998, z: 997 } };
Copy after login

you can access the property x like this:

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

Undefined Properties

If an attempted property reference results in an undefined property, it will return undefined (not null or false). For instance:

foo['c']['q'] === null // returns false
foo['c']['q'] === false // returns false
foo['c']['q'] === undefined // returns true
Copy after login

The above is the detailed content of How to Access JavaScript Object Properties Using a String for the Property Name?. 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