Home > OS >  How can I create a dynamic object in a literal?
How can I create a dynamic object in a literal?

Time:05-11

I have an object which includes several fields, most values are strings (constants) but I also want to use a variable (populated using some state)

const {order} = this.state;

myObject={{
    fieldA: 2,
    fieldB: ${order.value}
}}

I tried different variation of the above (with/without single quotes, etc.) but I am never able to set the value I need.

CodePudding user response:

You are adding 2 brackets for an object which is not valid and no need of template literal.

const { order } = this.state;

const myObject = {
  fieldA: 2,
  fieldB: order.value,
};

CodePudding user response:

You have used two braces ('{}') which are not needed. The code should be like below

const myobject = {fieldA: 2, fieldB: order.value};
  • Related