Sometimes, we want to create object using variables for property name with JavaScript.
In this article, we’ll look at how to create object using variables for property name with JavaScript.
How to create object using variables for property name with JavaScript?
To create object using variables for property name with JavaScript, we can use the computed property name syntax.
For instance, we write
const create = (propertyName) => {
const myObject = { [propertyName]: "value" };
return myObject;
};
to define the create
function that takes the propertyName
string parameter.
In it, we use the return value of propertyName
as the property name.
And we set its value to 'value'
.
Conclusion
To create object using variables for property name with JavaScript, we can use the computed property name syntax.