Home >Web Front-end >JS Tutorial >How do I access an object that contains spaces in the object key using JavaScript?

How do I access an object that contains spaces in the object key using JavaScript?

王林
王林forward
2023-08-25 20:05:131498browse

如何使用 JavaScript 访问对象键中包含空格的对象?

In this article, you will learn how to use JavaScript to access objects that contain spaces in their object keys. In this case, we use the bracket notation "[]" to access the object, or the dot notation (.) to access the object. Let’s look at a few examples below.

Example 1

In this example, we use square bracket notation [] to access the object.

console.log("The input object is a key value pair with key as firstName and value as Joseph");

const inputObject = {'firstName': 'Joseph'};
console.log("Using bracket notation to access value")
console.log(inputObject['firstName']); 

console.log("Using bracket notation to change the value to Alice")
inputObject['firstName'] = 'Alice';
console.log(inputObject);

illustrate

  • Step 1 - Define the key-value object and declare the value

  • Step 2 - Use bracket notation to access the value of the object. Show results.

  • Step 3 - Use bracket notation to change the value. Show new value.

Example 2

console.log("The input object is a key value pair with key as firstName and value as Joseph");

const inputObject = {'firstName': 'Joseph'};
console.log("Using dot notation to access value")
console.log(inputObject.firstName); 

illustrate

  • Step 1 - Define the key-value object and declare the values.

  • Step 2 - Use dot notation to access the value of the object. Show results.

The above is the detailed content of How do I access an object that contains spaces in the object key using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete