Access Object With Space In Key In JavaScript

In this article, we will cover how to access object with space in key in JavaScript. To achieve this, we will use the `[]` bracket notation in order to access the property of the object in `string` format and to be able to add the space in the key name.

First, let’s create an object and initialize it with a key that contains a space –

const user = {

"first name": "John",

  age: 30

};

Now, we have an object that contains two keys which are `first name` and `age`, and most commonly when we need to access a property inside of an object we use the `.` dot notation. So, for example let’s try to print the value of the `age` property on the console –

console.log(user.age);
print age property on console

As we can see, we used the `.` dot notation to access the `age` property in our `user` object. Now, what if we try to print the `first name` property using the same approach –

console.log(user.first name);
error when trying to access first name

We got an error as it is not expected to have spaces in the property name using the `.` dot notation. So, in order to avoid this we will need to use the `[]` bracket notation to access our property and pass in the property name as a `string`.

console.log(user["first name"]);
first name gets printed correctly

Using the `[]` bracket notation is not very common for accessing object properties, but in case the key name contains spaces, this is the appropriate way of accessing the key to be able to pass the key name as a `string`.

Finally, we can wrap this logic inside of a function so that we can dynamically access any property inside of an object and return its corresponding value

const getKeyValue = (object, key) => {

return object[key];

};

Now, if we call this function passing in the `user` object and `first name` as argument, we should expect to get the value of `first name` property as a result.

We will store the name of the `first name` key in a string variable.

const key = "first name";

console.log(getKeyValue(user, key));
first name property gets printed

Leave a Reply