How To Access An Object’s Key That Contains Hyphen

In this article, we will cover how to access an object’s key that contains hyphen `-`. To achieve this, we will use the `[]` bracket notation in order to access the property of the object in `string` format and to able to add the hyphen `-` in the key name.

Access An Object’s Key That Contains Hyphen

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

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);
property printed 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);
first-name property gets printed on console

We got an error as it is not expected to have hyphen `-` in the property name using the `.` dot notation. 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 property gets printed

Using the `[]` bracket notation is not very common in accessing object properties, but in case the key name contains hyphens, spaces, or symbols, 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));

Leave a Reply