Home >Web Front-end >JS Tutorial >How to Access JavaScript Object Properties with Spaces in their Keys?

How to Access JavaScript Object Properties with Spaces in their Keys?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 13:51:02366browse

How to Access JavaScript Object Properties with Spaces in their Keys?

Accessing JavaScript Objects with Spaced Keys

When working with JavaScript objects, accessing properties with spaces in their keys can be challenging. Here's a solution based on the provided object:

var myTextOptions = {
  'cartoon': {
     comic: 'Calvin & Hobbes',
     published: '1993'
  },
  'character names': {
    kid: 'Calvin',
    tiger: 'Hobbes'
  }
}

To access the "kid" property despite the space in the key, use ECMAscript's "bracket notation":

myTextOptions[ 'character names' ].kid;

Bracket notation allows you to enclose the key in square brackets, escaping any special characters or white spaces. This enables you to access the property as follows:

  1. Open square brackets [
  2. Specify the key name as a string enclosed in quotes: 'character names'
  3. Close square brackets ]
  4. Access the desired property: .kid

The result is the value of the "kid" property, which is "Calvin" in this case. You can use this notation to access any property with spaces in its key, allowing you to manipulate JavaScript objects with ease.

The above is the detailed content of How to Access JavaScript Object Properties with Spaces in their Keys?. 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