Categories
JavaScript Answers

How to create object using variables for property name with JavaScript?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.