How to Specify Brackets and Variables for Variable Properties in Javascript
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
This article summarizes how to specify brackets and variables for variable properties in Javascript.
Conclusion
const key = "variable"
object[key]
object["categories[]"]
How to Use Variables in Object Properties
Normally, when accessing data from an object like this,
object: {
key: "This is the key"
}
It is used like this,
object.key // This is the key
However, there are times when you want to dynamically use a variable as a property.
Solution
const variable = "key"
object[variable] // This is the key
This way, you can use a variable.
How to Use an Array (Square Brackets) in Object Properties
Sometimes you may want to specify something like
object.category[]
such as when using URL parameters.
However, this will result in a syntactic error.
Solution
Just like with variables before, you can do the following:
object["category[]"]
Summary
I have written about the syntax for using variables and square brackets in Javascript object properties.
I hope this can be helpful to someone.
I would be overjoyed if you could share this or leave feedback.
For comments or complaints, please contact me via Twitter DM.
That's it!