Home > Web Front-end > JS Tutorial > How do you access JavaScript object properties with spaces in their keys?

How do you access JavaScript object properties with spaces in their keys?

DDD
Release: 2024-11-11 01:21:03
Original
477 people have browsed it

How do you access JavaScript object properties with spaces in their keys?

Accessing JavaScript Objects with Spaced Keys

When declaring JavaScript objects, key names can contain spaces, but accessing them using the dot notation (e.g., myObject.child) can be challenging.

Problem:

Accessing properties of JavaScript objects with keys containing spaces, such as "character names" in the given object:

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

Solution:

To access such properties, use ECMAScript's "bracket notation":

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

The bracket notation allows you to use strings or expressions to access properties, resolving space issues. It works for both reading and writing object properties.

Additional Information:

  • For more comprehensive information on working with JavaScript objects, refer to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

The above is the detailed content of How do you access JavaScript object properties with spaces in their keys?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template