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."
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).
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"]
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!