Home >Web Front-end >JS Tutorial >How Do I Access JSON Object Properties Containing Dashes?

How Do I Access JSON Object Properties Containing Dashes?

Susan Sarandon
Susan SarandonOriginal
2024-11-26 19:29:13733browse

How Do I Access JSON Object Properties Containing Dashes?

Accessing JSON Object Properties with Dash Characters

This issue arises when attempting to retrieve a value from a JSON object where the property key contains a dash character (-). For example, consider the following JSON:

{
"profile-id":1234, "user_id":6789
}

If we try to access the "profile-id" property using dot notation (i.e., jsonObj.profile-id), we encounter the error "ReferenceError: 'id' is not defined."

Why Dot Notation Fails

In JavaScript, property keys in objects can only contain certain characters, including letters, numbers, and underscores. Dash is not one of these allowed characters. Dot notation automatically converts a property key with a dash to a subtraction expression (i.e., jsonObj.profile - id).

Solution: Using Bracket Notation

To overcome this limitation, we can use bracket notation to access object properties. Bracket notation allows us to specify the property key as a string. To access the "profile-id" property, we can use the following syntax:

jsonObj["profile-id"]

Example

Here's an example demonstrating how to use bracket notation to access a property with a dash character:

const jsonObj = {
  "profile-id": 1234,
  "user_id": 6789,
};

console.log(jsonObj["profile-id"]); // Output: 1234

The above is the detailed content of How Do I Access JSON Object Properties Containing Dashes?. 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