How to access a string “key” in Vue that includes hyphens, spaces or other special characters

holly bourneville
2 min readJul 11, 2023
Photo by Christin Hume on Unsplash

Usually in Vue, you would use the dot . notation to access a normal key, but when you have a key that has spaces or special characters you need to use the square bracket notation [] instead as the dot notation expects a valid JavaScript identifier as the key, and spaces and special characters are not allowed in identifiers.

In the example below, One of the keys in the attributes object is 'Size & Fit', which contains the value 'fits true to size'.

To access this value in the HTML template using Vue’s v-if directive, you use bracket notation attributes['Size & Fit'] instead of dot notation.

By using bracket notation, you can access the value associated with the key 'Size & Fit'. In this example the v-if="attributes['Size & Fit']" will display the corresponding HTML element if the expression resolves to a truthy value (which in this case, it does).

You can also access the value associated with the 'Size & Fit' key in your moustache tags to dynamically render the data in your html e.g <p>{{attributes[‘Size & Fit’]}}</p> on screen this would show ‘fits true to size’.

In the example below, you can also see how you would access a normal key, using the dot notation with the key productInfo

I hope this has helped!

Happy Coding! ⌨️

--

--

holly bourneville

Hi Im Holly! I’m from New Zealand. I’m in my first job as a Front End Web Developer and want to share my learnings and thoughts along the way!