How to access an object having spaces in the object’s key using JavaScript?


In this article, you will understand how to access an object having spaces in the object’s key using JavaScript. In such cases, we use bracket notation ‘[]’ to access objects or we use dot notation(.) to access objects. Let’s see a few examples below.

Example 1

In this example, let's use the bracket notation[] to access objects.

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);

Explanation

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

  • Step 2 − Use the bracket notation to access the value of the object. Display the result.

  • Step 3 − Use the bracket notation to change the value. Display the 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); 

Explanation

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

  • Step 2 − Use the dot notation to access the value of the object. Display the result.

Updated on: 16-Feb-2023

729 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements