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

How to Access JavaScript Objects with Spaces in Property Names?

Mary-Kate Olsen
Release: 2024-11-12 13:15:02
Original
809 people have browsed it

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

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;
Copy after login

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

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!

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