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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *