Home  >  Article  >  Web Front-end  >  How to Access JavaScript Objects with Spaces in Property Names?

How to Access JavaScript Objects with Spaces in Property Names?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 13:15:02733browse

How to Access JavaScript Objects with Spaces in Property Names?

Accessing JavaScript Objects with Spaces in Property Names

When working with JavaScript objects, you may encounter instances where the property keys contain spaces. Attempting to access these properties using dot notation (e.g., object.property name) will not work.

Consider the example:

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

To access the kid property, we cannot use myTextOptions.character names.kid. Instead, you need to employ ECMAscript's "bracket notation":

myTextOptions[ 'character names' ].kid;

Bracket notation allows you to specify any valid JavaScript expression within square brackets, including property names with spaces.

This notation can also be used for assigning values:

myTextOptions[ 'character names' ].newProperty = 'value';

For more information on working with objects in JavaScript, refer to the following resource:

  • [Working with Objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects)

The above is the detailed content of How to Access JavaScript Objects with Spaces in Property Names?. 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