Sometimes, we want to dynamically add variable name value pairs to JSON Object with JavaScript.
In this article, we’ll look at how to dynamically add variable name value pairs to JSON Object with JavaScript.
How to dynamically add variable name value pairs to JSON Object with JavaScript?
To dynamically add variable name value pairs to JSON Object with JavaScript, we use square brackets.
For instance, we write
const obj = {};
obj["name"] = value;
obj["anotherName"] = anotherValue;
to define the obj
object.
Then we add the name
and anotherName
properties into it.
This is the same as
const obj = { name: value, anotherName: anotherValue };
We can use keys that aren’t valid JavaScript property names with square brackets.
Conclusion
To dynamically add variable name value pairs to JSON Object with JavaScript, we use square brackets.