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
Release: 2024-11-11 13:51:02
Original
352 people have browsed it

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'
  }
}
Copy after login

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

myTextOptions[ 'character names' ].kid;
Copy after login

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!

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